所以我为整数制作了一个容器类,我想重载 =
运算符,以便我可以返回对象的深层拷贝。我的代码有效,但两个对象指向相同的地址。这是 main.cpp 文件:
int main (int argc, const char * argv[]) {
IntList cArray(5);
for (int i = 0; i < cArray.getLength(); i++) {
cArray[i] = (i + 1) * 10;
}
using namespace std;
for (int i = 0; i < cArray.getLength(); i++)
cout << cArray[i] << " ";
cout << endl << popped << endl;
IntList cArray2(4);
for (int i = 0; i < cArray2.getLength(); i++)
cArray2[i] = i * 5;
cArray2 = cArray;
cArray2[2] = 1000;
for (int i = 0; i < cArray.getLength(); i++)
cout << cArray[i] << " ";
cout << endl;
for (int i = 0; i < cArray2.getLength(); i++)
cout << cArray2[i] << " ";
cout << endl;
return 0;
}
这是 IntList
类的头文件:
class IntList {
private:
int _length;
int* _data;
public:
IntList(int length);
~IntList();
void erase();
void reallocate(int length); // Faster way to call erase() and resize()
void resize(int length);
void insert(int value, int index);
void prepend(int value);
void append(int value);
int pop(int index);
void removeBefore(int index); // Exclusive
void removeAfter(int index); // Exclusive
int getLength();
int indexOf(int value);
int& operator[](int index);
IntList operator=(IntList* source);
};
这是 IntClass
的 operator=()
方法的实现:
IntList IntList::operator=(IntList* source) {
_length = source->getLength();
reallocate(_length);
for (int i = 0; i < _length; i++) {
_data[i] = (*source)[i];
}
return *this;
}
最佳答案
您没有使用指向 IntList
的指针 - operator=
通常采用 const &
并返回对所分配实例的引用到。
IntList & IntList::operator=(IntList const & source) {
...
return *this;
}
请记住,您还需要一个复制构造函数:IntList(IntList const & source)
你可以创建一个 operator= ,它接受一个指向 IntList 的指针——只有你做了这样的事情才有效:
IntList l1;
IntList l2;
l1 = &l2;
这不是典型的用法,如果需要,您应该明确说明,例如void IntList::copyFrom(IntList const *)
在这种情况下。
你应该做的其他改变:
添加这个:
int operator[](int index) const;
使这些常量:
int getLength() const;
int indexOf(int value) const;
关于c++ - 重载 = 运算符时返回对象的深层拷贝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5436893/