C++:没有匹配的调用函数:为什么需要一个空的构造函数?

jer*_*253 3 c++ constructor default-constructor c++11

当我尝试编译以下代码时:

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() {

}
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

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
Run Code Online (Sandbox Code Playgroud)

似乎需要一个没有类 a 参数的构造函数。我不明白为什么,唯一一次我创建类型为 a 的对象时,我调用了以 int 作为参数的构造函数。

我知道解决方案是添加一个没有参数的构造函数。但为什么 ?

谢谢你的回答,最好的问候,

杰罗姆

son*_*yao 8

在构造函数中bmya=a(i2);是分配(但不initializtion)。在进入构造函数体之前,mya尝试进行默认初始化但a没有默认构造函数。

正如您所说,您可以为 添加一个默认构造函数a,然后mya将默认初始化,然后在 的构造函数中分配b

更好的方法是mya成员初始化列表中进行初始化

b::b(int i2) : mya(i2) {
//           ^^^^^^^^^
  j=2*i2; // this could be moved to member initializer list too
}
Run Code Online (Sandbox Code Playgroud)