c++ - 如何通过 std::vector<T> 的子类的重载赋值运算符进行深度复制?

标签 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;
}

最佳答案

对于您的问题,我不是 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

关于c++ - 如何通过 std::vector<T> 的子类的重载赋值运算符进行深度复制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9009740/

相关文章:

c++ - 做快捷方式 if 语句是否安全

c++ - 派生类如何访问基类的私有(private)数据成员?

c++ - 返回指针 vector 的类中的 const 方法

c++ - VC++ 11 中的 std::thread 类导致随机崩溃。任何解决方法?

c++ - 当我想在外面抓东西时无法编译 lambda

c++ - 传递函数的返回值作为引用

c++ - Qt库——静态成员函数的线程安全

java - 函数式接口(interface)中继承对象类方法有什么用,例如toString、equals

具有泛型参数基础的 Java 泛型参数

c++ - 为什么函数比较器不能像在排序中那样在优先级队列中工作?