我的计划是制作一个简单的加法计算器,然后从那里继续。 请记住,这是我编码的第一天。
#include <iostream>
#include <string>
using namespace std;
int a;
int b;
int sum;
string ans;
class CalcClass{
public:
int add (int a, int b) {
cout << "Pick the numbers you want to add" << endl;
cin >> a >> b;
sum = a + b;
return sum;
}
};
添加了 string ans;
(在顶部)。现在我得到一个 “错误:没有匹配函数调用 'CalcClass::add()'”
如果我已经创建了 calcObject
并使用 calcObject.add();
来调用该函数,为什么会这样说?
void pickFunction(){
cout << "What Function do you want to do? \n Add, Subtract, multiply, or divide? ";
cin >> ans;
if (ans == "add"){
CalcClass calcObject;
calcObject.add();
}
int main(){
pickFunction();
cout << "Your answer is : " << sum << endl;
return 0;
}
最佳答案
ans
需要类型(可能是 string
),add
需要引号("add"
),CalcClass.calcObject;
需要是 CalcClass calcObject;
。
“点”语法 (x.y
) 用于访问存储在对象内部的数据或函数,而不是类(例如 calcObject.add();
而不是 CalcClass.add();
)。
另外,正如 Mahesh 所说,pickFunction();
需要在 main
中。这应该如下所示:
void pickFunction(){
//code
}
int main() {
pickFunction();
//...
}
关于c++ - 错误 : two or more data types in declaration of function?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11353283/