【问题标题】:Declaring a member object without calling its default constructor声明成员对象而不调用其默认构造函数
【发布时间】:2019-11-03 12:00:18
【问题描述】:

我有两个班级: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]);
    ....
    ....
}

输出是

调用了无效的空构造函数

调用了有效的构造函数

如何在不调用 Motor 的空构造函数的情况下定义类 Generator 以拥有 Motor 的实例,直到稍后?

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

【问题讨论】:

  • Re: 'motor = Motor(filename); // 这里的初始化`——注释是错误的。该行是一个assignment

标签: c++ oop constructor


【解决方案1】:

您需要在Generator 构造函数中使用intialization list 构造:

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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-13
    • 1970-01-01
    • 1970-01-01
    • 2012-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多