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了对象,我也可以使用类的构造函数在其上调用构造函数。如何在已定义的类实例上调用构造函数?fsecond

4

2 回答 2

0

该对象first f;是 的成员second。这意味着每个都second包含一个first. 所以在创建 a 的过程中secondfirst必须创建 a 。您的 mem-initializer指定了在创建对象时f(x,y)如何创建。fsecond

于 2016-07-31T19:14:14.520 回答
0

当在函数中定义变量时,您可以混合不同的概念:

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

并声明为 a classor中的字段struct

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

于 2016-08-01T13:32:31.170 回答