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

Declaring a member object without calling its default constructor

本文关键字:默认 构造函数 调用 成员对象 声明      更新时间:2023-10-16

我有两个类: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

}

这是电机类的定义:

class Motor {
public:
Motor();
Motor(string filename);
}
Motor::Motor() {
cout << "invalid empty constructor called" << endl;
}
Motor::Motor(string filename) {
cout << "valid constructor called" << endl;
}

这是我的main()函数:

int main(int argc, char* argv[]) {
Generator generator = Generator(argv[1]);
....
....
}

输出为

名为的无效空构造函数

名为的有效构造函数

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

我不得不包含空构造函数,因为g++拒绝在没有它的情况下编译。

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

Generator::Generator(string filename) : motor(filename) // initialization here
{
// nothing needs to do be done here
}

您的原始代码实际上在做什么:

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
}