正在调用默认构造函数,但没有对其的引用

问题描述 投票:0回答:3

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

#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的默认构造函数,但是为什么呢?我正在使用的唯一Entity对象是使用使用1个参数的构造函数构建的。

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

c++ constructor initializer-list
3个回答
1
投票

Example构造函数内部,已经需要构造成员变量ent。错误就是这种构造。


0
投票

当显式定义任何构造函数时,隐式定义的默认构造函数将被删除并且不可用。


0
投票

在此构造函数的主体内

© www.soinside.com 2019 - 2024. All rights reserved.