我想使用OOP方式将两个数字相加。我是C ++的新手,因此需要您的帮助。
#include <iostream>
#include <string>
using namespace std;
class RunwalsClass{
public: // public function
void setName(string x){
name = x;
}
string getName(){
return name;
};
private: // good programming practice to make it private
string name;
};
class MyClass{
public:
void setSaying(string y){
CoolSaying = y;
}
string getSaying(){
return CoolSaying;
}
private:
string CoolSaying;
};
class FavSitcom{
public:
void setSitcom(string z){
BreakingBad = z;
}
string getSitcom(){
return BreakingBad;
}
private:
string BreakingBad;
};
class AddClass{
public:
void setNumbers(int a, int b){
int answer = a + b;
}
int getAddition(){
return answer;
}
private:
int answer;
};
int main(){
RunwalsClass RunwalsObject;
RunwalsObject.setName("Sir Buckey Wallace");
cout << RunwalsObject.getName() << endl;
MyClass MyObject;
MyObject.setSaying("Preaching to the choir! \n");
cout << MyObject.getSaying();
FavSitcom MyNewObject;
MyNewObject.setSitcom("My favorite Sitcom is: Breaking Bad \n");
cout << MyNewObject.getSitcom();
AddClass NewObject;
NewObject.setNumbers("answer: \n");
cout << AddObject.getAddition();
return 0;
}
error: #include <iostream>
#include <string>
using namespace std;
class RunwalsClass{
public: // public function
void setName(string x){
name = x;
}
string getName(){
return name;
};
private: // good programming practice to make it private
string name;
};
class MyClass{
public:
void setSaying(string y){
CoolSaying = y;
}
string getSaying(){
return CoolSaying;
}
private:
string CoolSaying;
};
class FavSitcom{
public:
void setSitcom(string z){
BreakingBad = z;
}
string getSitcom(){
return BreakingBad;
}
private:
string BreakingBad;
};
class AddClass{
public:
void setNumbers(int a, int b){
int answer = a + b;
}
int getAddition(){
return answer;
}
private:
int answer;
};
int main(){
RunwalsClass RunwalsObject;
RunwalsObject.setName("Sir Buckey Wallace");
cout << RunwalsObject.getName() << endl;
MyClass MyObject;
MyObject.setSaying("Preaching to the choir! \n");
cout << MyObject.getSaying();
FavSitcom MyNewObject;
MyNewObject.setSitcom("My favorite Sitcom is: Breaking Bad \n");
cout << MyNewObject.getSitcom();
AddClass NewObject;
NewObject.setNumbers("answer: \n");
cout << AddObject.getAddition();
return 0;
}
报告的错误:
error: no matching function for call to 'AddClass::setNumbers(const char [10]) note: candidate: void AddClass::setNumbers(int, int) note: candidate expects 2 arguments, 1 provided.
答案 0 :(得分:0)
是的,因此您的函数setNumbers()需要提供两个整数参数,即NewObject.setNumbers(5,10);它将数字设置为15。您提供的字符串文字“ answer:\ n”不相同,因此无法编译。
答案 1 :(得分:0)
主要,您正在将字符串作为参数传递给setNumbers方法。这行主要是错误的:
NewObject.setNumbers("answer: \n");
您的setNumbers函数需要声明两个整数。试试:
int a = 10;
int b = 5;
NewObject.setNumbers(a, b);
在OOP学习过程中祝您好运!
编辑: 同样,在setNumbers函数中,您不得重新声明答案,因为此变量是类成员。删除int,只需在setNumbers中使用答案即可。