2016-07-31 84 views
0
class first{ 
    int fa,fb; 

    public: 
     first(); 
     first(int x,int y); 
     void display(); 
}; 

first::first():fa(0),fb(0){ 
     } 

first::first(int x,int y):fa(x),fb(y){ 
} 

void first::display(){ 
    cout<<fa<<" "<<fb; 
} 

class second{ 
    first f; 
    int sa,sb; 

    public: 
     second(); 
     second(int x,int y,int a,int b); 
     void display(); 
}; 

second::second():sa(0),sb(0){ 
} 

second::second(int x,int y,int a,int b):f(x,y),sa(a),sb(b){ 
} 

void second::display(){ 
    cout<<"The Numbers are "; 
    f.display(); 
    cout<<" "<<sa<<" "<<sb<<endl; 
} 

如果已經提出此問題,請致歉。對象定義後調用構造函數定義

這是一個演示C++中嵌套類的工作的簡單代碼。 但是,在類second,對象f,即使它已被定義之前,我可以使用second類的construtor調用它的構造函數。 如何在已經定義的類的實例上調用構造函數?

+1

嵌套類或內部類是別的東西。這裏你只是有作文。 – aschepler

+2

這裏沒有嵌套類。 – DeiDei

回答

0

對象first f;second的成員。這意味着每個second包含一個first。因此在創建second的過程中,必須創建first。您的內存初始化程序f(x,y)指定了如何在創建second對象時創建f

0

你混用不同的概念,在一個函數中定義的變量:

void foo() 
{ 
    Foobar f; // f is defined and default initialized here 
    Foobar d { 123 }; // d is defined and initialized with 123 
} 

,並宣佈爲場內的classstruct

struct boo { 
    Foobar f; // f is declared as member of type boo and how it will be 
       // initialized will be known in boo's constructor 
       // not here 

    boo() {} // f is default constructed 
    boo(int i) : f { i } {} // f is initialized with i 
}; 

更糟糕的是你在C++ 11您可以將參數傳遞給現場構造函數:

struct boo { 
    Foobar d { 123 }; // d would be initialized with 123 if otherwise is not set in boo's constructor 

    boo(int i) : d { i } {} // 123 is ignored and d is initialized with i 
    boo() {} // d { 123 } is used 
}; 

所以即使你將參數傳遞給字段字段初始化的方式仍然在boo的構造函數中定義。