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

标签 c++ c++11 constructor default-constructor

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

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 的构造函数中分配.

更好的方法是初始化myamember 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/

相关文章:

c++ - 调试断言失败 : Invalid Null Pointer

c++ - unique_ptr 中原始指针的默认删除器

c++ - 错误地使用 move 的值

c++ - 右值引用不会将类型和类别混合在一起吗?

constructor - 如何解决 Haxe 中的 'Duplicate Constructor' 错误?

c++ - 使用范围解析运算符时在构造函数中调用虚方法是否安全?

c++ - 为只读 QPlainTextEdit 设置灰色背景颜色

c++ - MPI 可执行文件和共享标准输入

java - Java中字符串数组的复制构造函数

c++ - 避免窗口标题