我有一个类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/