C++ 构造函数没有匹配函数
c++ constructor no matching function
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
}
相关文章:
- "error: no matching function for call to"构造函数错误
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 选择要调用的构造函数
- 如何委托派生类使用其父构造函数?
- makefile对我的名称空间对象/函数/构造函数的不确定引用
- 没有可调用的匹配函数(构造函数),候选函数不同于对给定类型的引用
- C++库制作,隐藏在标头中没有友元的析构函数/构造函数
- 从另一个成员函数/构造函数调用C++构造函数是否执行初始值设定项列表
- 在另一个函数/构造函数 [C++] 中初始化后使变量只读
- std::调用函数时找不到函数构造函数
- 显式调用基类析构函数/构造函数合法吗
- 函数构造函数和nullptr
- 用委托构造函数构造函数
- 虚函数构造函数和调用虚函数时会发生什么
- 一些Qt函数/构造函数参数的内存管理
- 使用for_each或std::transform时,c++函函数构造函数是如何被调用的?
- std函数构造函数初始化