【发布时间】:2019-11-03 12:00:18
【问题描述】:
我有两个班级:Generator 和 Motor。
这是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]);
....
....
}
输出是
调用了无效的空构造函数
调用了有效的构造函数
如何在不调用 Motor 的空构造函数的情况下定义类 Generator 以拥有 Motor 的实例,直到稍后?
我必须包含空构造函数,因为g++ 拒绝在没有它的情况下进行编译。
【问题讨论】:
-
Re: 'motor = Motor(filename); // 这里的初始化`——注释是错误的。该行是一个assignment。
标签: c++ oop constructor