【问题标题】:Why is my struct constructor, which contains other structs, not working?为什么我的包含其他结构的结构构造函数不起作用?
【发布时间】:2021-08-07 17:52:33
【问题描述】:

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

没有匹配的函数调用'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,错误会用“Point”替换“Vector”。此外,构造函数可以完美地工作,而无需声明任何这些变量。 这可能是一个非常愚蠢的忽视。帮助。

【问题讨论】:

  • 你的 Body 构造函数也应该使用成员初始化列表语法,就像你的 PointVector 一样。这将修复错误
  • 如果这是一个有效的用例,你也可以给 Vector 一个默认构造函数

标签: c++ struct constructor physics


【解决方案1】:

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

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 没有默认构造函数。

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

【讨论】:

  • v(Vector(0,0)), a(Vector(0,0))可以简化为v(0,0), a(0,0)
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2014-07-03
    • 2011-07-06
    • 1970-01-01
    • 2021-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多