为什么我的包含其他结构的结构构造函数不起作用?

Why is my struct constructor, which contains other structs, not working?

我正在尝试创建一个计算直线运动的基本物理模拟。 当我尝试向 Body 结构添加构造函数时,它显示以下错误:

no matching function to call to 'Vector::Vector()'

代码如下:

struct Point{
    int x,y;
    Point(int _x, int _y) : x(_x), y(_y)
    {
    }
};
struct Vector{
    int value, direction;
    Vector(int _value, int _direction) : value(_value), direction(_direction)
    {

    }
};
struct Body{
    std::string ID;
    int m;
    Vector v, a;
    Point pos;

    Body(std::string _ID = "NONE", int _m = 0, Point _pos = Point(0, 0))
    {
        ID = _ID;
        m = _m;
        pos = _pos;
        v = Vector(0, 0);
        a = Vector(0, 0);
    }
};

我完全不知道为什么会这样。 我刚刚发现如果我在 va 之前声明 pos,错误将替换 'Vector' 与 'Point'。此外,构造函数无需声明任何这些变量即可完美运行。 这可能是一个非常愚蠢的忽视。帮助。

这两件事,为结构 VectorPoint 编写默认构造函数,以及将 Body 构造函数编写为成员初始值设定项列表,既可以单独工作也可以一起工作。 非常感谢。

在执行构造函数体之前初始化成员。因此,构造函数主体是初始化成员的错误位置。改为使用成员初始化列表:

Body(std::string _ID = "NONE", int _m = 0, Point _pos = Point(0, 0))
: ID(_ID), m(_m), v(0,0), a(0,0), pos(_pos) {
}

在您的代码中,因为您没有为成员指定初始化程序,所以在构造函数主体运行之前默认初始化它们。但是 Vector 没有默认构造函数。

请注意,成员是按照它们在 class 中列出的顺序进行初始化的。通常编译器会在初始化列表中的顺序不同时发出警告。