環路

2012-12-12 44 views
-1

我用下面的類拷貝構造函數調用:環路

#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; 
} 

然而,編譯器似乎總是推同一個對象在列表中。我認爲對拷貝構造函數的調用會阻止...

我錯了嗎?我是否需要使用創建對象的方式(並因此在某處管理其銷燬的痛苦)?

+3

你的代碼甚至不應該編譯(因爲它被定義爲一個數組,所以你不能分配給'cells')。基於你看起來想要的東西,你根本不需要定義一個拷貝構造函數(即,編譯器會合成一個拷貝構造函數來正確地拷貝'cells')。 –

+2

-1代表假碼。沒有編譯器會通過這個。甚至沒有Turbo C++或Visual C++ 6.0。如果您沒有實際向我們展示您的代碼,我們如何能夠幫助您解決代碼中的問題? –

+0

代碼已更正。對不起,引入錯誤 –

回答

1

您遇到不確定的行爲,因爲你使用std::array雖然忘記

return listA; 

你最好。如果你選擇保持這種方法,你還需要一個賦值操作符。

我假設你的實際成員是int* cells;

+1

是不是一個編譯器應該抱怨缺少返回語句?一個Java編譯器會,但我不記得有關C++。 –

+0

@ Code-Guru no ... –

+0

對不起...代碼更正 –