简体   繁体   English

没有用于C ++调用的匹配函数

[英]No matching function for call in C++

I am trying to learn the concept of classes in C++. 我试图学习C ++中的类的概念。 I have wrote some code to test what I know, when compiling the code, the first error was: "no matching function for call to 'base::base()' base base1, base2;" 我编写了一些代码来测试我所知道的,在编译代码时,第一个错误是:“没有匹配函数来调用'base :: base()'base base1,base2;”

I don't know why! 我不知道为什么!

Here is the whole code: 这是整个代码:

#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;
}

you can use 您可以使用

base base1, base2;

only when there is way to use the default constructor of base . 只有当有方法使用base的默认构造函数时。 Since base has explicitly defined a constructor that is not default, the default constructor is not available any more. 由于base已明确定义了非默认的构造函数,因此默认构造函数不再可用。

You can solve this in several ways: 你可以通过几种方式解决这个问题:

  1. Define a default constructor: 定义默认构造函数:

     base() : x(0), y(0) {} // Or any other default values that make more // sense for x and y. 
  2. Provide default values of the arguments in the constructor you have: 在您拥有的构造函数中提供参数的默认值:

     base(int a = 0, int b = 0); 
  3. Construct those objects using valid arguments. 使用有效参数构造这些对象。

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

base base1, base2; attempts to construct two base objects using the default constructor for base (that is, base::base() . base does not have a default constructor, so this does not compile. 试图构造两个base使用默认构造对象base (即, base::base() base不具有默认的构造,所以这不会编译。

To fix this, either add a default constructor to base (declare and define base::base() ), or use the 2-argument constructor that you have defined, as follows: 要解决这个问题,可以在base (声明和定义base::base() )中添加默认构造函数,或者使用已定义的2参数构造函数,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM