【发布时间】:2018-07-09 07:10:37
【问题描述】:
鉴于BaseClass 和SomeClass 类(实现operator= 和copy c'tor),我编写了以下类:
class DerivedClass : public BaseClass {
SomeClass* a1;
SomeClass* a2;
public:
// constructors go here …
~DerivedClass() { delete a1; delete a2;}
// other functions go here ...
};
我的问题是:我怎样才能实现DerivedClass 类的operator=?我怎样才能实现这个类的copy c'tor?
我想通过以下方式实现operator=:
DerivedClass& operator=(const DerivedClass& d) {
if (this==&d) return *this;
SomeClass* tmp1 = new SomeClass (*(d.a1));
SomeClass* tmp2 = NULL;
try {
tmp2 = new SomeClass(*(d.a2));
} catch (const std::exception& e) {
delete tmp1;
throw e;
}
delete this->a1;
delete this->a2;
this->a1 = tmp1;
this->a2 = tmp2;
return *this;
}
但是我不确定解决方案,特别是BaseClass的字段呢?
另外,如何实现DerivedClass的copy c'tor?我可以用operator= 做吗?
【问题讨论】:
标签: class c++11 operator-overloading copy-constructor derived-class