如何让类中的函数查看字符串分配的内容

  • 本文关键字:字符串 分配 函数 c++
  • 更新时间 :
  • 英文 :


我知道这对我们来说将是一段噩梦般的代码,但我正在与类作斗争,并努力变得更好。

我得到这个错误:

main.cpp:38:9: error: use of undeclared identifier 'nemesis'
if (nemesis == "p") {

显然,这不是一个好的代码,是的,我可以对它进行更好的编码,但我如何让代码从main()访问nemesis

#include <iostream>
using namespace std;
class Calculator {
public:
void NumberSet(double input, double input2);
double Multiplication(double value, double secondvalue);
double Division(double valie, double secondvalue);
double Simple(double value, double secondvalue);
void PlusorMinus(string name);
void Word(string name);
private:
double num;
double num2;
};
void Calculator::NumberSet(double input, double input2) {
this->num = input;
this->num2 = input2;
}
double Calculator::Multiplication(double value, double secondvalue) {
return value * secondvalue;
}
double Calculator::Division(double valie, double secondvalue) {
return valie / secondvalue;
}
void Calculator::Word(string name) {
string nemesis = name;
}
double Calculator::Simple(double value, double secondvalue) {
if (nemesis == "p") {
return value + secondvalue;
}
else {
return value - secondvalue;
}
}
int main() {
string punyword;
string nemesis;
int num1;
int num2;
Calculator calculator;
cout << "Would you like to use this complex complicator, puny human? Type yes or no" << endl;
cin >> punyword;
if (punyword == "yes") {
cout << "Multiplication? type M and 2 numers like that M 2 3, similar things can be performed for division, sum, substraction!!! " << endl;
cin >> nemesis, num1, num2;
calculator.Word(nemesis);
if (nemesis == "M") {
cout << calculator.Multiplication(num1,num2) << endl;
}
else if (nemesis == "D") {
cout << calculator.Division(num1,num2) << endl;
}
else {
cout << calculator.Simple(num1,num2) << endl;
}  
}
else {
cout << "very funny" << endl;
}
}

只需将Calculator::Word()方法内部的nemesis更改为Calculator类本身的成员,例如:

class Calculator {
public:
...
double Simple(double value, double secondvalue);
...
void Word(string name);
private:
string nemesis;. // <-- move it here
...
};
void Calculator::Word(string name) {
nemesis = name;
}
double Calculator::Simple(double value, double secondvalue) {
if (nemesis == "p") {
return value + secondvalue;
}
else {
return value - secondvalue;
}
}

相关内容

  • 没有找到相关文章

最新更新