我有一个继承自微软类的类,因此无法更改,我希望我的派生类在其复制构造函数和复制分配运算符中具有相同的行为。问题是,在复制构造函数中,您可以在初始化列表中调用基类的构造函数,但在运算符中,这不是一个选项。如何正确地在赋值运算符中重新创建此行为?只在运算符重载的主体中调用基类的构造函数是否足够?
附加说明:基类继承自CObject,该类的operator=()和复制构造函数被设置为私有和未实现的方法,因此不幸的是任何对它们的调用都将导致编译错误。
以下是一个简化的代码示例:
类声明:
以下是一个简化的代码示例:
类声明:
class Base
{
protected:
int baseInt;
public:
Base(int);
}
class Derived : public Base
{
public:
Derived(const Derived& other);
Derived& operator=(const Derived& rhs);
private:
int derivedInt;
}
派生类成员函数:
// Copy Constructor
Derived(const Derived& other) : Base(5)
{
derivedInt = other.derivedInt;
}
// Copy Assignment Operator
Derived& operator=(const Derived& rhs)
{
if (&rhs != this)
{
derivedInt = other.derivedInt;
return *this;
}
}
编辑:更新了语法并添加了CObject注释
Base(5);
只是创建一个临时的Base
对象,然后立即销毁它... - Oliver Charlesworth