试图初始化结构的构造函数中的初始化列表

Initialisation lists in constructors trying to initialize a structure

本文关键字:初始化 列表 构造函数 结构      更新时间:2023-10-16

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

非常感谢任何建议,

查看类结构成员的默认init值

要么在构造函数中初始化它

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

给结构一个构造函数:

class Floor_plan
{
private:
    unsigned int width;
    unsigned int height;
    struct floor_size {
        unsigned int x;
        unsigned int y;
        floor_size( int ax, int ay ) : x(ax), y(ay) {}
    };
    floor_size floor;
public:
    Floor_plan() : width(0), height(0), floor(0,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();
};

IMHO,除非你真的需要结构是POD,否则总是提供一个构造函数是一个很好的做法——它可以简化所有的事情。

您只能初始化floor,它直接在正在构建的对象中。

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

如果您启用了C++11支持,您可以使用floor{0, 0}[或者,不太明确地说,使用floor { },类似于其他人提到的floor()建议]

class floor_plan {
    struct floor_size { int x, y; } floor;
public:
    floor_plan() : floor{0, 0} { }
    floor_plan(int i, int j) : floor{i, j} { }
};

考虑到构造函数中有多余的大括号,我怀疑这就是您想要的语法。不需要显式构造函数(尽管您现在可以在不牺牲POD状态的情况下添加一个构造函数,如果这对您很重要的话)。

您可以NEVER使用dot(.)进行初始化!声明floor的构造函数。

struct floor_size
{
  floor_size(int, int);
}floor;

并在初始值设定项列表中使用相同的值。

Floor_plan () : floor_size(0,0) ...

最简单的方法是为floor_size类删除一个构造函数并调用该构造函数。

Floor_plan():宽度(0)、高度(0),楼层(0,0){};