gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 22:07:20 25 4
gpt4 key购买 nike

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

}

这是 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;
}

这是我的 main() 函数:

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

输出为

invalid empty constructor called

valid constructor called

如何定义类 Generator 以获得 Motor 的实例,而不调用 Motor 的空构造函数,直到稍后?

我必须包含空构造函数,因为如果没有它,g++ 拒绝编译。

最佳答案

您需要使用 intialization listGenerator 构造函数中进行构造:

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
}

关于c++ - 声明成员对象而不调用其默认构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58679941/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com