标签:style blog http color 使用 os
以面向对象的思想和简单工厂模式,写一个C++计算器程序,代码如下:
#include <iostream> using namespace std; class Operation { public: Operation(double left, double right) { lhs = left; rhs = right; } const double GetLeft() const { return lhs; } const double GetRight() const { return rhs; } void SetLeft(const double left) { lhs = left; } void SetRight(const double right) { rhs = right; } virtual double Calculate() = 0; // 纯虚函数 protected: double lhs; double rhs; }; class Add : public Operation { public: Add(double left, double right) : Operation(left, right) {} double Calculate() { return lhs + rhs; } }; class Sub : public Operation { public: Sub(double left, double right) : Operation(left, right) {} double Calculate() { return lhs - rhs; } }; class Mul : public Operation { public: Mul(double left, double right) : Operation(left, right) {} double Calculate() { return lhs * rhs; } }; class Div : public Operation { public: Div(double left, double right) : Operation(left, right) { try { if (right == 0) throw runtime_error("The divisor cannot be 0\n"); } catch (const runtime_error &e) { cout << e.what() << endl; throw; } } double Calculate() { return lhs / rhs; } }; // 工厂函数 Operation* FactoryFunction(double left, double right, char op) { switch (op) { case '+': return new Add(left, right); break; case '-': return new Sub(left, right); break; case '*': return new Mul(left, right); break; case '/': return new Div(left, right); break; default: throw runtime_error("Operation invalid!"); break; } } int main() { Operation *add = FactoryFunction(11, 22, '+'); Operation *sub = FactoryFunction(25, 32, '-'); Operation *mul = FactoryFunction(11, 11, '*'); Operation *div = FactoryFunction(50, 8, '/'); cout << add->GetLeft() << " + " << add->GetRight() << " = " << add->Calculate() << endl; cout << sub->GetLeft() << " - " << sub->GetRight() << " = " << sub->Calculate() << endl; cout << mul->GetLeft() << " * " << mul->GetRight() << " = " << mul->Calculate() << endl; cout << div->GetLeft() << " / " << div->GetRight() << " = " << div->Calculate() << endl; div->SetLeft(40); cout << div->GetLeft() << " / " << div->GetRight() << " = " << div->Calculate() << endl; // 别忘记销毁指针 delete add; delete sub; delete mul; delete div; system("pause"); return 0; }
标签:style blog http color 使用 os
原文地址:http://blog.csdn.net/nestler/article/details/37738095