g++(GCC)4.6.0

我有下面的类,我试图在构造函数的初始化列表中进行初始化。

class Floor_plan
{
private:
    unsigned int width;
    unsigned int height;

    struct floor_size {
        unsigned int x;
        unsigned int y;
    } floor;

public:
    Floor_plan() : width(0), height(0), floor.x(0), floor.y(0) {} {}
    Floor_plan(unsigned int _width, unsigned int _height, unsigned int _x, unsigned int _y);
    ~Floor_plan() {};

    unsigned int get_floor_width();
    unsigned int get_floor_height();
    void set_floor_width(unsigned int _width);
    void set_floor_height(unsigned int height);

    void print_floorplan();
};

我正在尝试将初始值设置为一个结构。但是,我一直收到以下错误:
expected ‘(’ before ‘.’ token

我也尝试过以下方法:
Floor_plan() : width(0), height(0), Floor_plan::floor.x(0), Floor_plan::floor.y(0) {}

但是,这导致以下错误:
expected class-name before ‘.’ token

非常感谢任何建议,

最佳答案

参见default init value for struct member of a class

您可以在构造函数中初始化它

Floor_plan() : width(0), height(0), floor() {
  floor.x = 1;
  floor.y = 2;
}

或者,您为该结构创建一个构造函数,并在初始化列表中使用它。
struct floor_size {
    unsigned int x;
    unsigned int y;
    floor_size(unsigned int x_, unsigned int y_) : x(x_), y(y_) {}
} floor;

Floor_plan() : width(0), height(0), floor(1, 2) {}

10-08 09:25
查看更多