1

メンバー オブジェクトがコンストラクターの初期化リストに表示されdataない場合dataは、既定のコンストラクターによって構築されます。

コンストラクターの初期化リストにある場合は、単純にdata 指定された値に初期化されます。これは、作成するためのコンストラクター呼び出しがないことを意味しdataますか? その場合、新しいオブジェクトはどのようにdata構築されますか?

4

3 に答える 3

2

If data appears in the constructor's initialization list, then it is simply initialized to the given value.

No, it is initialised using whatever arguments are supplied. If it has a class type, then the arguments are passed to a suitable constructor.

Does this imply that there is no constructor call for creating data?

No. If it has a class type, then initialisation is done by calling a constructor.

于 2013-10-24T11:04:03.813 に答える
0

When you're initializating data in the constructor's initialization list, its parametrized constructor is called.
Example:

#include <iostream>
#include <string>

class Data {
public:
    Data(int firstArg, std::string mSecondArg)
    {
        std::cout<<"parameterized constructor called"<<std::endl;
    }
};

class SomeClass {
public:
    SomeClass(int firstArg, std::string secondArg) : data(firstArg, secondArg) {}
private:
    Data data;
};

int main(int argc, char** argv) {
    SomeClass someObj = new SomeClass(0, new std::string("empty"));
    return 0;
}

With this code you will get output
parameterized constructor called

于 2013-10-24T11:03:47.730 に答える