Class “我如何实施?”;运算符=”;及;副本c';tor“;在这种情况下正确吗?

Class “我如何实施?”;运算符=”;及;副本c';tor“;在这种情况下正确吗?,class,c++11,operator-overloading,copy-constructor,derived-class,Class,C++11,Operator Overloading,Copy Constructor,Derived Class,给定类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 ... }; 我的问题是:如何实

给定类
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 ...
};
我的问题是:如何实现类
派生类的
操作符=
?我如何实现这个类的
copy c'tor

我想通过以下方式实现
操作符=

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;
}  
但我不确定解决方案,特别是
基类的字段如何

此外,如何实现
DerivedClass
copy c'tor
?我可以用
operator=
来实现吗?

我的建议是不要实现它们,而是去实现它们。例如,(如果可接受共享
a1
a2
的所有权),则可以轻松实现这一点

但是,如果您必须实现自己的复制构造函数和复制赋值运算符,那么您首先需要调用父类构造函数或运算符,然后再进行自己的复制

对于构造函数,使用构造函数初始值设定项列表:

DerivedClass(DerivedClass const& other)
    : BaseClass(other), a1(new SomeClass(*other.a1)), a2(new SomeClass(*other.a2))
{}
部分
a1(new SomeClass(*other.a1)
使用其复制构造函数创建一个新的
SomeClass
对象,并初始化成员
a1
以指向新对象

最后一部分也应该是对复制赋值运算符的提示,因为它也可以在那里使用:

DerivedClass& operator=(DerivedClass const& other)
{
    if (this != &other)
    {
        // First let the parent copy itself
        BaseClass::operator=(other);

        // Deep copy of the members
        delete a1;
        a1 = new SomeClass(*other.a1);

        delete a2;
        a2 = new SomeClass(*other.a2);
    }

    return *this;
}

但是在异常的情况下,
this
的值并没有保留,也就是说,如果我们在执行
a2=newsomeclass(*(other.a2))时
我们将获得
std::bad_alloc
,因此我们希望保持关于
字段的信息,就像在开始一样,不是吗?此外,通过
操作符=
?@软件存在实现
复制构造函数的方法,几乎所有异常都是不可恢复的。如果您没有足够的内存来分配对象,那么继续到底有什么意义呢?好吧,有些情况下你可以释放内存,但是对象创建和赋值都必须重新进行,你必须在比复制构造函数和赋值操作符更高的层次上进行。好的,只有为了理解,如果我想的话,我才能这样做
BaseClass::operator=(其他);
在更新
a1
a2
?或它必须在开始时?@软件\t它可以是任何顺序。