声明成员对象而不调用其默认构造函数

Ahm*_*mad 2 c++ oop constructor

我有两节课:GeneratorMotor。这是的简化版本Generator

class Generator {
private:
    Motor motor;    // this will be initialized later
                    // However, this line causes the constructor to run.
public: 
    Generator(string);
}

Generator::Generator(string filename) {
    motor = Motor(filename);     // initialisation here

}
Run Code Online (Sandbox Code Playgroud)

这是Motor类的定义:

class Motor {
public:
    Motor();
    Motor(string filename);
}

Motor::Motor() {
    cout << "invalid empty constructor called" << endl;
}
Motor::Motor(string filename) {
    cout << "valid constructor called" << endl;
}
Run Code Online (Sandbox Code Playgroud)

这是我的main()功能:

int main(int argc, char* argv[]) {
    Generator generator = Generator(argv[1]);
    ....
    ....
}
Run Code Online (Sandbox Code Playgroud)

输出是

无效的空构造函数调用

有效的构造函数称为

如何GeneratorMotor不调用的空构造函数的情况下将类定义为具有的实例Motor,直到以后呢?

我必须包括空的构造函数,因为g++拒绝没有它的编译器。

Shl*_*oim 5

您需要在构造函数中使用初始化列表Generator构造:

Generator::Generator(string filename) : motor(filename) // initialization here
{
    // nothing needs to do be done here
}
Run Code Online (Sandbox Code Playgroud)

您原始代码的实际作用是:

Generator::Generator(string filename) /* : motor() */ // implicit empty initialization here
{
    motor = Motor(filename) // create a temp instance of Motor
    //    ^------------------- copy it into motor using the default operator=()
                            // destruct the temp instance of Motor
}
Run Code Online (Sandbox Code Playgroud)