【问题标题】:Problem accessing member of struct inside a class访问类中结构成员的问题
【发布时间】:2022-01-04 05:28:38
【问题描述】:

我正在用 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)
    {}

任何帮助表示赞赏。

【问题讨论】:

    标签: c++ class struct initialization aggregate-initialization


    【解决方案1】:

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

    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}
        {}
    

    【讨论】:

    • ...别忘了初始化isAfloat!默认应该是true
    猜你喜欢
    • 2013-05-31
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 2014-11-30
    • 2014-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多