c++ - 正在调用默认构造函数而不引用它
问题描述
为什么以下代码不起作用:
#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();
会导致我的代码以不同的方式工作(我在屏幕上看不到任何打印。
解决方案
在构造函数内部,已经需要构造Example
成员变量。ent
错误所指的正是这种结构。
解决方案是使用构造函数初始化程序列表,您已在所示示例中将其注释掉。
至于
Example s1();
这声明s1
为一个不带参数并按值返回Example
对象的函数。
推荐阅读
- python - 为什么 invalid_dict = {[1, 5]: 'a', 5: 23} 无效但 valid_dict = {(1, 5): 'a', 5: [23, 6]} 在 python 中有效?
- c++ - 从链表中删除返回垃圾值
- java - 为什么创建对象的副本仍然会改变原始对象的实例变量?
- mongodb - MongoDB Atlas 和本地数据库的实时同步
- python - Python - 将 CSV 读取为字符串列表
- regex - 如何在飞镖中使用正则表达式从字符串中提取日期时间对象?
- sql - 正确的连接顺序 - 建立一个新的查询
- typo3 - Typo3 9: Second Language 使用后备模式显示两种翻译的内容
- android - 当我打开 android studio 项目时,它在文件中显示不同的字符
- java - 不要将 Android 上下文类放在静态字段中。这是内存泄漏。为什么?