[英]C++ Initialize nested struct in constructor's initialization list?
struct B
{
int hh;
int ii;
};
struct A
{
B b_memberVar;
void *p_data;
};
struct C
{
A array[13];
int bb;
int cc;
int dd;
int ee;
int ff;
int gg;
};
struct D
{
C c_memberVar;
int aa;
};
class XYZ
{
XYZ();
D m_DMemberVar;
int zz;
}
XYZ::XYZ():
m_DMemberVar(
({{{
{{0,0},nullptr},
{{0,0},nullptr},
{{0,0},nullptr},
{{0,0},nullptr},
{{0,0},nullptr},
{{0,0},nullptr},
{{0,0},nullptr},
{{0,0},nullptr},
{{0,0},nullptr},
{{0,0},nullptr},
{{0,0},nullptr},
{{0,0},nullptr},
{{0,0},nullptr}
},0,0,0,0,0,0},0}),
zz(0)
){}
How do I initialize a nested struct that's a class member variable on the constructor's initialization list? 如何初始化作为构造函数初始化列表上的类成员变量的嵌套结构? I have tried using a lot of nested {} as shown as an example above but that produced syntax errors.
我尝试使用大量的嵌套{},如上面的示例所示,但产生了语法错误。 The errors give "expected an expression" and "expected a ")" "
错误给出“期望的表达式”和“期望的”)”
Well, you have a ton of errors with your class definitions: 好吧,您的类定义有很多错误:
But, once those are fixed, it really is just a case of matching your braces. 但是,一旦固定好了,那实际上只是匹配括号的一种情况。
Here we go! 开始了!
struct D
{
int D_MemberVar;
};
struct C
{
int* c_ptrMemberVar;
};
struct B
{
C c_memberVar;
D* d_ptrMemberVar;
};
struct A
{
B b_memberVar;
int int_memberVar;
};
class XYZ
{
A m_memberVar;
int z;
public:
XYZ();
};
XYZ::XYZ()
: m_memberVar{
{ // A::b_memberVar
{ // B::c_memberVar
nullptr // B::c_ptrMemberVar
},
nullptr // B::d_ptrMemberVar
},
3 // A::int_memberVar
}
, z(0)
{}
int main()
{
XYZ xyz;
}
I suspect the key is that you were trying to use A
's constructor, but there is no non-default constructor in that class. 我怀疑关键是您尝试使用
A
的构造函数,但是该类中没有非默认构造函数。 So you needed {}
at the top level too. 因此,您也需要在最高级别使用
{}
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.