C++ 构造函数没有匹配函数

c++ constructor no matching function

本文关键字:函数 构造函数 C++      更新时间:2023-10-16
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 ) ;
}

怎么了?

如果我用StructA s = StructA( x ) ;替换_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) 
{
}

如果我用StructA s = StructA( x ) ;替换_s = StructA( x ) ;并将其从私有中删除,它可以正常工作。为什么?

因为_s现在是一个自动变量,只存在于MainStruct构造函数中。它不再是MainStruct类成员,因此在进入构造函数的主体之前不需要对其进行初始化。请注意,当它编译时,它使_s对您完全无用,因为它仅在MainStruct构造函数中可见,并且将在构造函数结束时被销毁。

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
}