【发布时间】:2019-02-01 10:34:30
【问题描述】:
我有一个基类
class Base{
public:
virtual ~Base();
};
我从 Base 派生了两个类:
class D1:public Base{
//...some fields
//assignment operator, it does the deep copy of the members
D1& operator=(const D1&);
};
class D2:public Base{
//...some fields
//assignment operator, it does the deep copy of the members
D2& operator=(const D2&);
};
接下来,我主要有两个对象,比如说D1。问题是从不调用覆盖的赋值运算符,但是调用 base 的默认运算符。我尝试在Base 中将赋值运算符设为虚拟,但没有帮助。
D1 *d1 = new D1();
D1 *d1_another = new D1();
//this doesn't work:
d1 = d1_another
D2 *d2 = new D2();
D2 *d2_another = new D2();
//this doesn't work:
d2 = d2_another
UPD 我也想知道怎么处理
Base *d1 = new D1();
Base *d1_another = new D1();
//?
d1 = d1_another
【问题讨论】:
-
你分配指针...this way
-
@user1810087
*d1 = *d1_another? -
@PavloKovalov:试试看。
-
没错,见链接:)
-
赋值和派生类不能很好地配合。将它们结合起来往往是一个设计错误。您永远不会分配任何基础或派生对象。您只是在分配指针。
标签: c++