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ます。既に定義されているクラスのインスタンスでコンストラクターを呼び出すにはどうすればよいですか?

4

2 に答える 2

0

オブジェクトfirst f;は のメンバーですsecond。つまり、すべてsecondに が含まれていfirstます。したがって、 を作成する過程で、 を作成するsecond必要firstがあります。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
}

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 に答える