cod*_*er9 4 c++ operator-overloading
我想要一份当前运行的实例的副本.
当我更改副本中的值时,原始对象也会受到影响.该副本充当实例.
怎么避免这个?我需要创建一个调用对象的独立副本.
Set operator+(Set s){
Set temp = *this;
for(int i=0; s.elements[i] != '\0'; i++){
temp(s.elements[i]);
}
temp.elements[0] = 'X'; // <- this affects calling object also :(
return temp;
}
Run Code Online (Sandbox Code Playgroud)
问题是Set temp = *this;制作浅拷贝,而不是深拷贝.您必须修改类的复制构造函数和赋值运算符,Set以便它们复制所有成员/包含的对象.
例如:
class Set
{
public:
Set()
{
elements = new SomeOtherObject[12];
// Could make elements a std::vector<SomeOtherObject>, instead
}
Set(const Set& other)
{
AssignFrom(other);
}
Set& operator=(const Set& other)
{
AssignFrom(other);
return *this;
}
private:
void AssignFrom(const Set& other)
{
// Make copies of entire array here, as deep as you need to.
// You could simply do a top-level deep copy, if you control all the
// other objects, and make them do top-level deep copies, as well
}
SomeOtherObject* elements;
};
Run Code Online (Sandbox Code Playgroud)
并不是说你的函数已经生成了两个副本,因为它接受了它的参数并返回每个副本的结果:
Set operator+(Set s);
Run Code Online (Sandbox Code Playgroud)
所以你不必复制s,因为它已经被复制了.我想这是不自觉的,所以你可能想要了解如何将对象传递给函数以及如何从 C++中的函数返回对象.
但是,您报告的问题暗示您的复制构造函数无法正常工作.您是否实现了复制构造函数,或者您是否使用了编译器提供的复制构造函数?