简单工厂实现计算器功能

来源:互联网 发布:php超链接 编辑:程序博客网 时间:2024/05/17 02:02

#include <iostream>using namespace std;//实现功能:输入两个数和运算符号,得到结果enum EFunType{FUNC_NONE=0,FUNC_PLUS,FUNC_MINUS,FUNC_MULTIPLE,FUNC_DIVISION};class CFunction{protected:double m_numberA;double m_numberB;public:virtual ~CFunction(){}void SetNumberA(double numA){m_numberA = numA;}void SetNumberB(double numB){m_numberB = numB;}virtual double GetResult(){return 0;}};class CPlus:public CFunction{public:double GetResult(){return m_numberA+m_numberB;}};class CMinus:public CFunction{public:double GetResult(){return m_numberA-m_numberB;}};class CMultiple:public CFunction{public:double GetResult(){return m_numberA*m_numberB;}};class CDivision:public CFunction{public:double GetResult(){if(m_numberB==0){cout << "The dividen is 0!"<<endl;return 0;}elsereturn m_numberA/m_numberB;}};class COperationFactory{private:string m_func;CFunction *m_pfunc;EFunType m_GetType(){if(m_func == "+"){return FUNC_PLUS;}else if(m_func == "-"){return FUNC_MINUS;}else if(m_func == "*"){return FUNC_MULTIPLE;}else if(m_func == "/"){return FUNC_DIVISION;}elsereturn FUNC_NONE;}public:COperationFactory(string func){m_func=func;m_pfunc = NULL;}CFunction* GetOperate(){EFunType etype;etype = m_GetType();switch(etype){case FUNC_PLUS:m_pfunc = new CPlus;break;case FUNC_MINUS:m_pfunc = new CMinus;break;case FUNC_MULTIPLE:m_pfunc = new CMultiple;break;case FUNC_DIVISION:m_pfunc = new CDivision;break;default:m_pfunc = NULL;cout <<"INVALID INPUT~"<<endl;break;}return m_pfunc;}};int main(){string operat;double numA,numB;cout<<"Please enter first number:"<<endl;cin>>numA;cout<<"Please enter second number:"<<endl;cin>>numB;cout<<"Please enter your operator choice(+/-/*//):"<<endl;cin>>operat;COperationFactory factory(operat);CFunction *opera = factory.GetOperate();opera->SetNumberA(numA);opera->SetNumberB(numB);cout<<"Result is "<<opera->GetResult()<<endl;return 0;}

原创粉丝点击