struct structA
{
StructA( const int a ) { ... } ;
}
然后我的主要结构:
·H
struct MainStruct
{
MainStruct( int x, int y ) ;
private :
int _x ;
int _y ;
StructA _s ;
}
*。CPP
StructA( int x, int y) : _x(x) , _y(y)
{
_s = StructA( x ) ;
}
有什么问题?
如果我将_s = StructA( x ) ;
替换为StructA s = StructA( x ) ;
并将其从私有中移除,则可以正常工作。那是为什么?
In constructor ....
no matching function for call to 'StructA'
_y( y)
答案 0 :(得分:1)
在输入构造函数的主体之前,必须完全构造所有类成员。无法构造_s
,因为它未在member initializer list中使用适当的参数指定,并且没有默认构造函数供编译器与自动生成的代码一起使用。
快速修复:使用成员初始化列表
MainStruct( int x, int y) : _x(x) , _y(y), _s(x)
{
}
如果我将
_s = StructA( x ) ;
替换为StructA s = StructA( x ) ;
并将其从私有中移除,则可以正常工作。那是为什么?
因为_s
现在是Automatic variable,只存在于MainStruct
构造函数中。它不再是MainStruct
类成员,因此在进入构造函数体之前不需要初始化它。请注意,虽然这会编译,但它会使_s
完全无用,因为它只在MainStruct
构造函数中可见,并且会在构造函数的末尾被销毁。
答案 1 :(得分:0)
struct structA
{
StructA( const int a ) { ... } ;
}
意味着你需要为它的构造函数提供一个int。
你MainStruct
不这样做:
StructA( int x, int y) : _x(x) , _y(y)
{ //by here we need to default construct the _s but cannot
_s = StructA( x ) ;
}
您可以在初始化程序中对此进行排序:
StructA( int x, int y) : _x(x) , _y(y), _s(x)
{
//^--- look
}