2013-01-24 98 views
2

我有下面的代碼,我不明白,爲什麼在創建對象B,類A的構造函數不稱爲.......我將非常感謝您的一點help.hank。C++類組成,爲什麼構造函數不被調用?

#include <iostream> 
using namespace std; 

class MyClass 
{ 
    int x; 
public: 
    MyClass(int y);       
    MyClass(MyClass &my) 
    { 
     x = my.x; 
     cout << "My class created by copy" << endl; 
    } 
}; 
MyClass::MyClass(int y) 
{ 
    x = y; 
    cout << "My class created" << endl; 
} 

class A { 
    MyClass k; 
    public: 
     A(MyClass &my) : k(my) { 
      cout << "A created" << endl; 
     } 
}; 
class B { 
    A data; 
    public: 
     B(A& aa) : data(aa) 
     { 
      cout << "B created" << endl; 
     } 
}; 
int main() 
{ 
    MyClass obj(100); 
    A a(obj); 
    B b(a);      
    return 0; 
} 

執行:

My class created 
My class created by copy 
A created 
My Class created by copy 
B created 
+1

'**'在代碼視圖中標出東西不適用於標記。請編輯! –

+2

爲什麼downvotes傢伙?新用戶。歡迎來到SE。 –

+2

爲什麼downvote? **我真的很討厭** [tag:C++]相關問題的積極downvoting,沒有留下任何評論(至少在這裏我已經注意到了)。給一些額外的標籤似乎可以放鬆這種行爲,這可能適用於第一次或低信譽的OP。給他們一個機會的人!嘗試幫助! –

回答

6

A的拷貝構造函數被調用,而不是構造您所定義。既然你既沒有定義也沒有刪除它,所以默認的構造函數被調用。默認構造函數將調用每個成員變量的複製構造函數;我相信這是按照聲明的順序。

相關問題