如何通过重载std :: vector <t> </t>子类的赋值运算符来进行深层复制

时间:2012-01-25 20:26:30

标签: c++ inheritance stl

我有一个来自Step的课程std::vector<unsigned int>。我需要重载赋值运算符,因为在从静态方法返回的值的赋值中使用了深拷贝。我无法弄清楚如何将rhv的所有元素复制到this中:

class Step : public std::vector<unsigned int>
{
public:
    friend std::ostream& operator<<(std::ostream& outStream, const Step& step);
    Step& operator =(const Step& rhv);
    static Step fromString(const std::string &input);
    // Something like: Step x = Step::fromString("12 13 14 15 16");
private:
    double time;
    double pause;
    unsigned int id;
    std::string name;
};

然后重载=

Step& Step::operator =(const Step& rhv)
{
    time = rhv.time;
    pause = rhv.pause;
    id = rhv.id;
    // How should I copy contents of rhv to `this` safely?
    return *this;
}

3 个答案:

答案 0 :(得分:4)

我不是100%肯定你的问题,但我认为你问的是打电话给父母operator=。在这种情况下,您有两个选择:

std::vector<unsigned int>::operator=(rhv); //either explicitly call the parent assignment op
*static_cast<std::vector<unsigned int>*>(this) = rhv; //or cast this to parentclass and call assignment on that

当然在您向我们展示的代码中,您没有进行任何手动资源处理,因此我不明白您为什么要编写自己的赋值运算符,编译生成的一个应该没问题。除此之外,如果您编写自己的赋值运算符,您可能需要前往rule of three并编写自己的复制构造函数和析构函数(至少在C ++ 03中,由于可移动但C ++ 11可能会略有不同)不可复制的课程。)

另一个旁注:大多数标准库不是为了派生而设计的,所以你可能想重新考虑你的设计需要你继承std::vector

答案 1 :(得分:3)

继承标准容器通常被认为是一个坏主意,因为它们不是设计用作基类(除了其他东西之外没有虚拟析构函数)。几乎在每种情况下都优选成分。

假设您已决定进入此雷区,则可以使用static_cast调用父分配运算符。

*static_cast<std::vector<unsigned int>*>(this) = rhv;

并且不要忘记分配name

答案 2 :(得分:1)

在这种情况下,您实际上不必重载operator=,因为默认生成的一个将正常工作(通过依次分配每个成员和基类)。

如果定义自己的运算符,则可以调用基类运算符,就像调用另一个基类函数一样

std::vector<unsigned int>::operator=(rhv);

让矢量处理自己的赋值。