为什么以下代码不起作用:
#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();
会导致我的代码以不同的方式工作(我在屏幕上看不到任何打印。