访问 class 中的结构成员时出现问题

Problem accessing member of struct inside a class

我正在用 C++ 制作战舰棋盘游戏,在访问我在 类.

中声明的结构时遇到问题
class Ship {
    typedef struct {
        int x;
        int y;
    }Start;
    typedef struct {
        int x;
        int y;
    }End;
    bool isAfloat;
    
    Start _start;
    End _end;

public:
    Ship(int start_x, int start_y, int end_x, int end_y);

我尝试了所有可以想到的方式,但我显然遗漏了一些东西。

Ship::Ship(int start_x, int start_y, int end_x, int end_y):
    _start.x(start_x), //error, expected "(" where the "." is 
    _start.y(start_y),
    _start.x(end_x),
    _end.y(end_y)
    {}

感谢任何帮助。

您需要直接初始化整个对象,而不是单独初始化它们的成员。例如

Ship::Ship(int start_x, int start_y, int end_x, int end_y):
    isAfloat ( ...true_or_false... ), // better to initialize it too
    _start {start_x, start_y}, 
    _end {end_x, end_y}
    {}

顺便说一句:从 C++20 开始,您可以使用 designated initializers 然后您可以将成员的名称指定为:

Ship::Ship(int start_x, int start_y, int end_x, int end_y):
    isAfloat ( ...true_or_false... ), // better to initialize it too
    _start {.x = start_x, .y = start_y}, 
    _end {.x = end_x, .y = end_y}
    {}