c++ - 初始化列表调用顺序 C++
问题描述
有这个结构:
struct Coordinates
{
int x;
int y;
Coordinates(int x_axis, int y_axis)
{
x = x_axis;
y = y_axis;
}
Coordinates()
{
std::cout << " CALL " << std::endl;
}
};
并且有这个类:
class Character
{
public:
bool canSpeak;
int hp;
float gold;
Coordinates position;
Character();
};
我想了解一件事(我知道类的成员按照声明它们的顺序进行初始化)。所以,如果我这样做:
Character::Character() : position(25, 32), canSpeak(1), hp(position.y), gold(position.x)
{
std::cout << gold << " " << hp << std::endl;
}
两者hp
和gold
都将包含垃圾值,但我想查看发生这种情况的时间轴,因为在大括号之前,所有类成员都应该被初始化(这意味着它们确实需要在 and 之间进行初始化:
,{
并且如果它们按顺序初始化出现,如何position.y
和position.x
被“使用”?
我希望在编译器能够使用Coordinates::Coordinates()
之前调用,但这并没有发生。所以我不明白按时间顺序会发生什么。Coordinates::Coordinates(int x_axis, int y_axis)
position.x
position.y
解决方案
推荐阅读
- javascript - 如何在 node.js 中使用需要用户名/密码认证的 REST api
- android - PageList 中的 BoundaryCallback 永远不会被调用
- asp.net-core - 在 ASP.NET Core 2.1 中将 Neo4j 驱动程序实例放在哪里?
- javascript - 带有离屏输入标签的角度复选框
- java - 线程“主”java.lang.NoSuchMethodException 中的异常
- node.js - npm live-server 不会自动重新加载
- css - 我正在应用 flex 属性,但它不会扩展或收缩
- python - 我的脚本无法点击某个网格
- android - 我想知道如何获取选中的checkboxin android studio的信息
- elasticsearch - Elasticsearch 在大型索引中搜索大量字段