当我尝试编译以下代码时:
class a {
int i;
public :
a(int);
};
class b {
a mya;
int j;
public:
b(int);
};
a::a(int i2) {
i=i2;
}
b::b(int i2) {
mya=a(i2);
j=2*i2;
}
int main() {
}
我收到以下错误:
prog.cpp:21:12: error: no matching function for call to ‘a::a()
b::b(int i2) {
^
prog.cpp:17:1: note: candidate: ‘a::a(int)
a::a(int i2) {
^
prog.cpp:17:1: note: candidate expects 1 argument, 0 provided
prog.cpp:1:7: note: candidate: ‘constexpr a::a(const a&)’
class a {
^
prog.cpp:1:7: note: candidate expects 1 argument, 0 provided
prog.cpp:1:7: note: candidate: ‘constexpr a::a(a&&)
prog.cpp:1:7: note: candidate expects 1 argument, 0 provided
似乎需要一个没有类 a 参数的构造函数。我不明白为什么,唯一一次我创建类型为 a 的对象时,我调用了以 int 作为参数的构造函数。
我知道解决方案是为 a 添加一个没有参数的构造函数。
但为什么 ?
谢谢您的回答,
此致,
杰罗姆
最佳答案
在 b
的构造函数中, mya=a(i2);
是赋值(但不是初始化)。在进入构造函数体之前,mya
试图默认初始化,但 a
没有默认构造函数。
正如您所说,您可以为 a
添加一个默认构造函数,然后 mya
将被默认初始化,然后在 b
的构造函数中分配.
更好的方法是初始化mya
在 member initializer list .
b::b(int i2) : mya(i2) {
// ^^^^^^^^^
j=2*i2; // this could be moved to member initializer list too
}
关于C++:没有匹配的调用函数:为什么需要一个空的构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62406373/