简体   繁体   中英

No matching function for call in C++

I am trying to learn the concept of classes in 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;"

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 . Since base has explicitly defined a constructor that is not default, the default constructor is not available any more.

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.

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 base1(2,3), base2(4,5);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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