首页 > 解决方案 > 正在调用默认构造函数而不引用它

问题描述

为什么以下代码不起作用:

#include <iostream>

class Entity
{
public:
    /*
    Entity()
    {
        std::cout << "Create Entity with default constructor" << std::endl;
    }
     */

    Entity(int x)
    {
        std::cout << "Create Entity with " << x << std::endl;
    }
};

class Example
{
    Entity ent;
    int age;

public:
    Example()
            //: ent(7), age(7)
    {
        ent=Entity(7);
        age=7;
    }
};

int main() {
    Example s1;
    return 0;
}

它说它需要实体的默认构造函数,但为什么呢?我使用的唯一 Entity 对象是使用使用 1 个参数的构造函数构建的。

另外,为什么更改Example s1;Example s1();会导致我的代码以不同的方式工作(我在屏幕上看不到任何打印。

标签: c++classconstructordefault-constructorctor-initializer

解决方案


在构造函数内部,已经需要构造Example成员变量。ent错误所指的正是这种结构。

解决方案是使用构造函数初始化程序列表,您已在所示示例中将其注释掉。


至于

Example s1();

这声明s1为一个不带参数并按值返回Example对象的函数。


推荐阅读