Home > Net >  Problem accessing member of struct inside a class
Problem accessing member of struct inside a class

Time:11-26

I am making a battleship board game in c and have issues accessing the struct that I have declated inside one of my classes.

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);

I have tried to do in every thinkable way but I'm clearly missing something here.

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

Any help appreciated.

CodePudding user response:

You need to initialize the whole object directly, not their members separately. E.g.

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

BTW: Since C 20 you can use designated initializers then you can specify members' name as:

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