2016-07-31 82 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的构造函数中定义。