#pragma once class Operation { public: Operation(void); ~Operation(void); public: double m_numberA; double m_numberB; public: virtual double GetResult()=0; }; struct OperateFactory { static Operation* CreateOperate(char operate); }; #include "Operation.h" #include <string> #include <exception> using namespace std; Operation::Operation(void) { this->m_numberA=0; this->m_numberB=0; } Operation::~Operation(void) { } //加法 class OperationAdd:public Operation { public: double GetResult() { double m_result=0; m_result=this->m_numberA+this->m_numberB; return m_result; } }; //减法 class OperationSub:public Operation { public: double GetResult() { double m_result=0; m_result=this->m_numberA-this->m_numberB; return m_result; } }; //乘法 class OperationMul:public Operation { public: double GetResult() { double m_result=0; m_result=this->m_numberA*this->m_numberB; return m_result; } }; //除法 class OperationDiv:public Operation { public: double GetResult() { double m_result=0; if (this->m_numberB==0) { throw new exception("除数不能为0"); return 0; } else { m_result=this->m_numberA/this->m_numberB; return m_result; } } }; Operation* OperateFactory::CreateOperate( char operate ) { Operation *oper; switch (operate) { case '+': oper=new OperationAdd; break; case '-': oper=new OperationSub; break; case '*': oper=new OperationMul; break; case '/': oper=new OperationDiv; break; } return oper; } // Factory.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <iostream> #include <string> #include "Operation.h" using namespace std; int _tmain(int argc, _TCHAR* argv[]) { //OperateFactory Ofactory; Operation *oper; oper=OperateFactory::CreateOperate('+'); oper->m_numberA=1121; oper->m_numberB=1111; double Result=oper->GetResult(); cout<<Result; delete oper; getchar(); return 0; }