将其java代码转化为Cpp 代码。
#include <iostream> #include <string> using namespace std; void func1() { cout << "please input number A:" << endl; long numberA; cin >> numberA; cout << "please input operate(+_*/):" << endl; char operate; cin >> operate; cout << "please input number B:" << endl; long numberB; cin >> numberB; switch (operate) { case‘+‘: cout << "result is : " << numberA + numberB << endl; break; case‘-‘: cout << "result is : " << numberA - numberB << endl; break; case‘*‘: cout << "result is : " << numberA * numberB << endl; break; case‘/‘: cout << "result is : " << (double)numberA / numberB << endl; break; } }
#include <iostream> #include <string> using namespace std; class Operation { protected: double numberA; double numberB; public: double GetNumberA(){ return numberA; } double GetNumberB(){ return numberB; } void SetNumbers(double value1, double value2){ numberA = value1; numberB = value2; } virtual double GetResult(){ return 0.0; } }; class OperationAdd : public Operation { public: double GetResult() { return numberA + numberB; } }; class OperationSub : public Operation { public: double GetResult() { return numberA - numberB; } }; class OperationMul : public Operation { public: double GetResult() { return numberA * numberB; } }; class OperationDiv : public Operation { public: double GetResult() { return numberA / numberB; } }; class OperationFactory { public: static Operation* CreateOperate(char operate){ Operation *p = NULL; switch (operate) { case‘+‘: p = new OperationAdd(); break; case‘-‘: p = new OperationSub(); break; case‘*‘: p = new OperationMul(); break; case‘/‘: p = new OperationDiv(); break; } return p; } }; void func2() { double a = 7.0; double b = 8.0; char op = ‘*‘; Operation* oper = OperationFactory::CreateOperate(op); oper->SetNumbers(a,b); cout << a << op << b << " equal " << oper->GetResult() << endl; }
时间: 2024-10-20 01:25:46