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)
在进入构造函数体之前,必须完全构造所有类成员。_s
无法构造,因为它没有在成员初始值设定项列表中指定适当的参数,并且没有供编译器与自动生成的代码一起使用的默认构造函数。
快速修复:使用成员初始值设定项列表
MainStruct( int x, int y) : _x(x) , _y(y), _s(x)
{
}
如果我更换
_s = StructA( x ) ;
与StructA s = StructA( x ) ;
和私人删除它,它工作正常。这是为什么?
因为_s
现在是一个仅存在于构造函数中的Automatic 变量MainStruct
。它不再是MainStruct
类成员,因此在进入构造函数体之前不需要对其进行初始化。请注意,在编译时,它对_s
您完全无用,因为它仅在MainStruct
构造函数中可见,并且将在构造函数结束时销毁。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句