1 我想用简单工厂实现简单的计算器,
在主函数输入左右运算数和运算符,在工厂类中通过运算符选择要调用的具体操作——加减乘除,加减乘除各自单独设计一个类,它们都继承自Operation类
2 代码如下
#include <iostream>
#include <cmath>
using namespace std;
class Operation
{
public:
Operation(double operandA,double operandB,char operate)
{
this->operandA=operandA;
this->operandB=operandB;
this->operate=operate;
}
protected:
double operandA;
double operandB;
char operate;
public:
void setOperandA(double operandA)
{
this->operandA=operandA;
}
void setOperandB(double operandB)
{
this->operandB=operandB;
}
void setOperate(char operate)
{
this->operate=operate;
}
double getOperandA()
{
return this->operandA;
}
double getOperandB()
{
return this->operandB;
}
char getOperate()
{
return this->operate;
}
virtual double getResult()=0;
};
class AddOperation:public Operation
{
public:
AddOperation(double operandA,double operandB,char operate):Operation( operandA, operandB, operate){}
double getResult()
{
return operandA+operandB;
}
};
class MinusOperation:public Operation
{
public:
MinusOperation(double operandA,double operandB,char operate):Operation( operandA, operandB, operate){}
double getResult()
{
return operandA-operandB;
}
};
class MultipleOperation:public Operation
{
public:
MultipleOperation(double operandA,double operandB,char operate):Operation( operandA, operandB, operate){}
double getResult()
{
return operandA*operandB;
}
};
class DivOperation:public Operation
{
public:
DivOperation(double operandA,double operandB,char operate):Operation( operandA, operandB, operate){
}
double getResult()
{
// cout<<operandB<<endl;
if(fabs(this->operandB)>1e-2)
{
return this->operandA/this->operandB;
}
return -1;
};
class OperationFactory{
public :
Operation *operation=NULL;
public:
Operation* createOperation(double operandA,double operandB,char opt)
{
switch(opt)
{
case '+':
{
AddOperation add(operandA,operandB,opt);
operation=&add;
}
break;
case '-':
{
MinusOperation minus(operandA,operandB,opt);
operation=−
}
break;
case '*':
{
MultipleOperation multiple(operandA,operandB,opt);
operation=&multiple;
}
break;
case '/':
{
DivOperation div(operandA,operandB,opt);
operation=÷
}
break;
default:
break;
}
return operation;
}
};
int main()
{
double oprA,oprB;
double result;
char opt;
cin>>oprA>>oprB>>opt;
// AddOperation add(oprA,oprB,opt);
// Operation *op=&add;
OperationFactory factory;
Operation *option=factory.createOperation(oprA,oprB,opt);
result=option->getResult();
cout<<result;
return 0;
}
3 问题
在具体操作——加减乘除的实现类中,如DivOperation中,若在该函数体内
判断除数operandB与0的关系语句前,加入
cout<<operandB<<endl;
这样一句话,operandB的值就会错误,导致计算结果也发生错误
比如输入10 10/时
不加这句话结果就对了,请问代码哪里出了问题?