标签:
#include<iostream> #include<string> #include<exception>//c++标准异常类型的库 using namespace std; bad_exception somethingwrong; //在c++中class默认的继承是private 而struct 默认的继承是public //static 类静态成员函数,即与对象无关,在类中的值不是因实例化某个对象而改变. class operation//运算类(基类) { public: double numberA; double numberB; virtual double GetResult()//虚函数GetResult来得到计算结果. { double result=0; return result; } }; //加减乘除类,继承自算法类(运算类的各个子类) class operationAdd:public operation { public: double GetResult() { return numberA+numberB; } }; class operationSub:public operation { public: double GetResult() { return numberB-numberA; } }; class operationMul:public operation { public: double GetResult() { return numberA*numberB; } }; class operationDiv:public operation { public: double GetResult() { if(numberB==0) throw somethingwrong; return numberA/numberB; } }; //运算工厂类 class operationFactory { public: static operation* createoperation(char operate) { switch(operate) { case ‘+‘: return new operationAdd; break; case ‘-‘: return new operationSub; break; case ‘*‘: return new operationMul; break; case ‘/‘: return new operationDiv; break; } } }; int main() { //客户端的程序 operation *a; a=operationFactory::createoperation(‘/‘); a->numberA=8; a->numberB=0; try{ cout<<a->GetResult()<<endl;} catch(bad_exception &) { cerr<<"B不应该为0"; cout<<endl; } system("pause"); return 1; }
标签:
原文地址:http://www.cnblogs.com/yanliang12138/p/4339990.html