-1

我在这里有这段代码:

class DerivedClass : public BaseClass {
    SomeClass* a1;
    Someclass* a2;
public:
    //constructors go here
    ~DerivedClass() { delete a1; delete a2;}
    // other functions go here ....
};

我的第一个问题如下:

  • 我可以在 "DerivedClass" 中写一个 "operator=" 吗?(如果你的答案是肯定的,你能告诉我怎么做吗?)

我的第二个问题是:

  • 如果上述答案是肯定的,您能否告诉我如何使用您事先编写的“operator=”(如果可能的话)制作“复制构造函数”?
4

2 回答 2

1

这是编写复制构造函数和赋值运算符的最佳方法,尊重“零规则”:

#include <optional>
class DerivedClass : public BaseClass
{
    std::optional<SomeClass> a1;
    std::optional<SomeClass> a2;
public:
    //constructors go here
};

编译器将为析构函数、复制构造函数和复制赋值运算符编写正确的代码。如果SomeClass是可移动的,您还将免费获得移动分配和移动构造函数。

如果SomeClass是多态的,你将需要一个clone()像 BogoIt 提到的函数。但即使在这种情况下,使用智能指针也很有价值(std::unique_ptr将是合适的)。

于 2013-07-01T16:02:41.160 回答
1

copy ctor 和 op= 的主体取决于您计划存储资源的方式:a1 和 a2 变量。如果您需要将它们复制到另一个类 - 您应该编写一些函数来制作您的 SomeClass 对象的完整副本。另一种情况——你可以简单地复制指针值——但是要非常小心你使用它们的方式,尤其是删除它们。共享资源问题的最简单解决方案是使用一些智能指针,例如 boost::shared_ptr 或 c++11 std::shared_ptr。

因此,如果您打算复制资源:

class DerivedClass : public BaseClass {
    SomeClass* a1;
    Someclass* a2;
public:

    // note: do not forget to assign zeroes to your pointers, unless  you use some kind of smart pointers
    DerivedClass()
    :a1(0), a2(0){}

    DerivedClass(const DerivedClass& d)
                :a1(0), a2(0)
    {
        *this = d;
    }

    DerivedClass& operator=(const DerivedClass& d)
    {
        if (this == &d)
            return *this;

        delete a1;
        a1 = d.a1->clone();

        delete a2;
        a2 = d.a2->clone();

        return *this;
    }


    //constructors go here
    ~DerivedClass() { delete a1; delete a2;}
    // other functions go here ....
};

您还需要 SomeClass 的 clone() 函数,该函数将复制您的对象: class SomeClass { public:

    SomeClass* clone() const
    {
        return new SomeClass();
    }
};
于 2013-07-01T15:48:02.603 回答