c++中没有匹配的调用函数

No matching function for call in C++

本文关键字:调用 函数 c++      更新时间:2023-10-16

我正在学习c++中类的概念。我写了一些代码来测试我所知道的,当编译代码时,第一个错误是:"没有匹配的函数调用' base::base() '"Base base1, base2;"

我不知道为什么!

完整代码如下:

#include <iostream>
using namespace std;
class base {
   int x, y;
  public:
  base (int, int);
  void set_value (int, int);
  int area () { return (x*y); }
};
base::base ( int a, int b) {
 x = a;
 y = b;
}
void base::set_value (int xx, int yy) {
 x = xx;
 y = yy;
}
int main () {
base base1, base2;
base1.set_value (2,3);
base2.set_value (4,5);
cout << "Area of base 1: " << base1.area() << endl;
cout << "Area of base 2: " << base2.area() << endl;
cin.get();
return 0;
}

可以使用

base base1, base2;

仅在有办法使用base的默认构造函数时使用。由于base显式地定义了一个非默认构造函数,因此默认构造函数不再可用。

你可以用几种方法解决这个问题:

  1. 定义默认构造函数:

    base() : x(0), y(0) {} // Or any other default values that make more
                           // sense for x and y.
    
  2. 在构造函数中提供参数的默认值:

    base(int a = 0, int b = 0);
    
  3. 使用有效的参数构造这些对象。

    base base1(2,3), base2(4,5);
    

base base1, base2;尝试使用base的默认构造函数(即base::base())构造两个base对象。base没有默认构造函数,因此无法编译。

要解决这个问题,可以向base添加一个默认构造函数(声明并定义base::base()),或者使用您已经定义的2参数构造函数,如下所示:

base base1(2,3), base2(4,5);