gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 02:46:26 25 4
gpt4 key购买 nike

我正在尝试学习 C++ 中类的概念。我写了一些代码来测试我所知道的,在编译代码时,第一个错误是:“没有匹配函数调用‘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);

关于c++ - 在 C++ 中没有匹配的调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23576738/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com