我用下面的類拷貝構造函數調用:環路
#include <list>
class A {
public:
A();
A(const A&);
~A();
list<A> createCopies();
private:
int *cells;
};
A::A() {
this->cells = new int[5];
for(unsigned int i = 0; i < 5; i++) {
this->cells[i] = 0;
}
}
A::(const A &oldA) {
this->cells = new int[5];
for(unsigned int i = 0; i < 5; i++) {
this->cells[i] = oldA.cases[i];
}
}
A::~A() {
delete[] this->cells;
}
list<A> A::createCopies() {
list<A> listA;
for(unsigned int i = 0; i < 3; i++) {
A newA = A(*this); // or A newA(*this)?
A.cells[i] = 1;
listA.push_back(newA);
}
return listA;
}
然而,編譯器似乎總是推同一個對象在列表中。我認爲對拷貝構造函數的調用會阻止...
我錯了嗎?我是否需要使用創建對象的方式(並因此在某處管理其銷燬的痛苦)?
你的代碼甚至不應該編譯(因爲它被定義爲一個數組,所以你不能分配給'cells')。基於你看起來想要的東西,你根本不需要定義一個拷貝構造函數(即,編譯器會合成一個拷貝構造函數來正確地拷貝'cells')。 –
-1代表假碼。沒有編譯器會通過這個。甚至沒有Turbo C++或Visual C++ 6.0。如果您沒有實際向我們展示您的代碼,我們如何能夠幫助您解決代碼中的問題? –
代碼已更正。對不起,引入錯誤 –