2014-01-09 42 views
1

所以,我構建了一個名爲Attribute的對象,該對象具有完整副本和空構造函數。 然後我建立了另一個叫Human的對象,它包含了Attribute對象。 當我嘗試構建人類(完全構造函數)不知何故它會自動調用屬性複製構造函數,我不知道爲什麼。帶複製構造函數的C++ does not工作良好

這裏是代碼:

char** d = new char*[3];  
    d[0] = new char[10]; 
    d[0] = "aa"; 
    d[1] = new char[10]; 
    d[1] = "bb"; 
    d[2] = new char[10]; 
    d[2] = "cc"; 

    Attribute *a = new Attribute(1.7, "blue", "white", "black", d, 3); 
    Human *h = new Human("Name", *a); 

當我使用調試器,並獲得該行:新人類(「名稱」,*一);它會自動進入此功能:

Attribute::Attribute(Attribute& copy)  
{ 
    Attribute(copy.height, copy.eyeColor, copy.skinColor, copy.hairColor, copy.diseases, copy.numOfDiseases); 
} 

這個函數結束後才能,開始了人類完全構造函數...

我希望你能幫助我....謝謝

+0

[規則三](http://stackoverflow.com/questions/11024438/rule-of-three-in-c)最有可能... –

+1

你真的需要分配'Human'和'Attribute'在堆上(即使用'new'並保持一個指針)?我的感覺是,你正在使用C++,就好像它在Java和這個不好的地方一樣。 –

+2

您正在泄漏內存。只要你不熟悉指針(甚至可以說是你),使用std :: string而不是char *。 – nvoigt

回答

7
Human *h = new Human("Name", *a); 
           ^----- Here it's passing in an Attribute by value 

因此調用屬性拷貝構造函數。

1

複製構造函數沒有初始化任何內容;它只是創建並銷燬一個本地臨時對象。

在C++ 11,你可以工作委託給另一個構造函數,你似乎想要做的事:

Attribute::Attribute(Attribute const & copy) : 
    Attribute(copy.height, copy.eyeColor, copy.skinColor, copy.hairColor, copy.diseases, copy.numOfDiseases) 
{} 

歷史上,你不得不重複其他構造的代碼,或者將它移動到由兩個構造函數調用的函數中。

你或許還希望通過引用採取構造函數的參數,使他們不需要被複制:

Human(std::string const & name, Attribute const & attribute); 

你也應該避免new,除非你真的需要它。你可能想要的東西更像

Attribute a(1.7, "blue", "white", "black", d, 3); 
Human h("Name", a); 

當你真的需要new(通常是因爲你希望對象活得比當前範圍,或有時爲多態性),使用RAII管理類型,如智能指針和容器而不是原始指針,以確保一旦你完成對象的正確刪除。雜耍原始指針是內存泄漏和其他災難的祕訣。

1

一個 - 是一個指針 *一個 - 就是價值

因此,如果你對人類的構造函數通過值

Human::Human(char* s, Attribute a) 

將複製的屬性和使用拷貝構造函數它需要幾秒鐘的參數。 如果你不想要這種行爲,你可以通過指針傳遞參數。

Human::Human(char* s, Attribute *a) 

,並調用它像這樣:

Attribute *a = new Attribute(1.7, "blue", "white", "black", d, 3); 
Human *h = new Human("Name", a); // this works with pointer now. Pointer will be copied, but the class will remain in the same memory and wouldn't be copied anywhere. 

如果你認爲它的行爲與正常價值和功能相似:

void f1(int a){ a++; cout << a; } 
void f2(int *a){ *a++; cout << *a; } 

int b = 4; 
f1(b); // It copies the value of local b to parameter a, increments local parameter a of f1 and prints it; It will print 5 
cout << b; // b will remain the same. It will print 4 
f2(&b); // It copies pointer, but both pointers &b and a point to the same variable b from this scope, and it's value is not copied 
cout << b; // As we've worked with pointers, it was incremented in f2. It will print 5 

請注意,你必須處理所有指針的責任。如果您手動創建了某些內容,請不要忘記它應該刪除的位置,以及在哪些情況下可能會發生泄漏。使用smart_pointers更容易。