g++ (GCC) 4.6.0 我有以下类,我正在尝试初始化构造函数的结构成员初始化列表
g++ (GCC) 4.6.0 I have the following class and I am trying to initialize structure member initialization list of my constructor
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() {};
}
在上面的代码中,
我们如何在不创建地板对象的情况下初始化floor_size结构成员....提前感谢您的回答。
您的结构floor_size
是POD(普通旧数据类型),因此您可以像这样初始化floor
成员:
Floor_plan() : width(0), height(0), floor()
{}
这将使用零,默认值或值初始化之一,我永远不知道哪个。
如果启用 C++11 支持(-std=c++0x
开关),则可以使用大括号初始化:
Floor_plan() : width(0), height(0), floor({10, 20})
{}
我认为您不需要初始化此结构。只需将其定义为类型成员
struct floor_size {
unsigned int x;
unsigned int y;
};
当您需要将宽度和高度重新解释为floor_size元素时,您可以创建一个floor_size对象,例如
floor_size floor = { width, height };
如果在结构floor_size前面使用 static 关键字,则可以使用类名进行初始化,如下所示,
Floor_plan::floor.x=100;
Floor_plan::floor.y=100;
Floor 已经是"类"(或结构)floor_size的对象。
你只需要一个用于初始化的构造函数。
例如:
class Floor_plan
{
private:
unsigned int m_width;
unsigned int m_height;
struct floor_size {
unsigned int m_x;
unsigned int m_y;
public: floor_size(int p_x,int p_y) : m_x(p_x),m_y(p_y) {}
} floor;
public:
Floor_plan() : m_width(0), m_height(0), floor(0,0) {}
Floor_plan(unsigned int _width, unsigned int _height, unsigned int _x, unsigned int _y);
~Floor_plan() {};
};
相关文章:
- 为什么std::vector和std::valarray初始化构造函数不同
- 初始化构造函数C++中结构的向量
- C++ 中常量属性的初始化构造函数错误
- 不正确的输出和变量未用Eclipse CDT初始化构造函数
- 如何使用嵌套初始化构造函数中的一维向量初始化矩阵
- 如何通过参数初始化构造函数中的数组?
- 是否有理由使用 malloc 初始化构造函数中的指针
- 如何在 c++ 中初始化构造函数中的二维数组
- 为什么初始化构造函数列表参数时会发生异常?
- 无法初始化构造函数
- 初始化构造函数的默认参数的优选方法是什么?
- 在C++17中使用空列表初始化构造函数时发生编译错误
- C++ 初始化构造函数初始化列表中的嵌套结构?
- 初始化构造函数c++中的向量
- g++ (GCC) 4.6.0 我有以下类,我正在尝试初始化构造函数的结构成员初始化列表
- 使用字符串文本初始化构造函数中的 std::array<char,x> 成员。海湾合作委员会错误?
- 初始化构造函数C++中函数的成员指针
- 在c++中初始化构造函数中的静态成员变量时出错
- memset()初始化构造函数中的对象
- 初始化构造函数C++中的成员向量