首页 > 解决方案 > 初始化列表调用顺序 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;
}

两者hpgold都将包含垃圾值,但我想查看发生这种情况的时间轴,因为在大括号之前,所有类成员都应该被初始化(这意味着它们确实需要在 and 之间进行初始化:{并且如果它们按顺序初始化出现,如何position.yposition.x被“使用”?

我希望在编译器能够使用Coordinates::Coordinates()之前调用,但这并没有发生。所以我不明白按时间顺序会发生什么。Coordinates::Coordinates(int x_axis, int y_axis)position.xposition.y

在此处输入图像描述

标签: c++

解决方案


推荐阅读