所以我为整数创建了一个容器类,我想重载=
运算符,以便我可以返回对象的深层副本。我的代码有效,但两个对象指向同一个地址。这是 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
'soperator=()
方法的实现:
IntList IntList::operator=(IntList* source) {
_length = source->getLength();
reallocate(_length);
for (int i = 0; i < _length; i++) {
_data[i] = (*source)[i];
}
return *this;
}