简体   繁体   English

如何使用带指针的转换构造函数?

[英]How do I use a conversion constructor with pointers?

I have a class C that can be converted to class A and a function that takes an A* as an argument. 我有一个可以转换为A类的CA以及一个以A*作为参数的函数。 I want to call it with a C* , but I can't seem to get a conversion constructor to work. 我想用C*来调用它,但似乎无法使转换构造函数正常工作。 I get: error: cannot convert 'C*' to 'A*' for argument '1' to 'void doSomething(A*)' . 我得到: error: cannot convert 'C*' to 'A*' for argument '1' to 'void doSomething(A*)' What am I doing wrong? 我究竟做错了什么?

class C {
};

class A {
public:
    A(C* obj) {}
};

void doSomething(A* object);

int main()
{
    C* object = new C();
    doSomething(object);
}

Conversion constructors can only be defined for user defined types , in your case A . 转换构造只能为用户定义类型定义,你的情况A However, they do not apply to fundamental types as pointers like A* . 然而,他们并不适用于基本类型的指针 A*

If doSomething was taking an A const& instead (or simply an A ) , then the conversion constructor would be invoked as you expect. 如果doSomething使用A const&代替(或简单地使用A ,则将按您的期望调用转换构造函数

If you main requirement is to be able to call the existing doSomething function, then you can do this: 如果您的主要要求是能够调用现有的doSomething函数,则可以执行以下操作:

int main()
{
    C* object = new C();
    A a(object);
    doSomething(&a);
    // May need to delete object here -- depends on ownership semantics.
}

You probably mean that you want C to be a subclass of A: 您可能是想让C成为A的子类:

class C : public A {
...
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM