nah*_*hpr 4 c++ operator-overloading assignment-operator
class B;
class A{
B *b;
public:
void operator= (B *b){
this->b = b;
}
};
B *b = new B()
A *a = new A();
a = b;
Run Code Online (Sandbox Code Playgroud)
我收到"无法转换B*为A*"错误.有没有解决的办法?
现在,如果有办法,如果我使用类似的东西:
a = NULL;
Run Code Online (Sandbox Code Playgroud)
将使用哪个运算符"="?
您operator=提供从a B*到a的分配A.您的代码不提供从a B*到a 的转换A*(如错误消息所示).因此,a=NULL不会使用您提供的赋值运算符,因为a它是指针,而不是A.您的代码允许从a B*到a分配A,例如A a= new B();.
如果您打算使用实际对象而不是指针,请*从代码中删除所有内容:
class B{};
class A{
B b;
public:
void operator= (const B& b){ //pass non-primitives by const reference
this->b = b;
}
};
B b;
A a;
a = b;
Run Code Online (Sandbox Code Playgroud)
如果你想使用指针,只有"有用"的方式分配B*到A*是,如果一个B对象从派生A.这似乎不是你在做什么,所以分配B*到A*将毫无意义在你的代码.