c++多态案例之计算器类
案例描述:利用普通技术和多态技术分别实现两个操作数进行运算的计算器类。
多态的优点:代码结构清晰;可读性强;利于前期和后期的扩展以及维护;
#include<iostream> using namespace std; //普通写法,如果想扩展,需要修改源码 //在实际开发中,提倡开闭原则,对扩展进行开发,对修改进行关闭 class Calculator { public: int num1; int num2; int getResult(string oper) { if (oper == "+"){ return num1 + num2; } else if (oper == "-") { return num1 - num2; } else if (oper == "*") { return num1 * num2; } else if (oper == "/") { return num1 / num2; } else { return -1; } } }; //利用多态实现计算器 class AbstractCalculator { public: int num1; int num2; virtual int getResult() { return 0; } }; class Add :public AbstractCalculator { int getResult() { return num1 + num2; } }; class Sub :public AbstractCalculator { int getResult() { return num1 - num2; } }; class Mul :public AbstractCalculator { int getResult() { return num1 * num2; } }; class Div :public AbstractCalculator { int getResult() { return num1 / num2; } }; void test() { Calculator cal; cal.num1 = 6; cal.num2 = 3; int res = cal.getResult("/"); cout<< res << endl; } void test2() { AbstractCalculator * cal = new Add; cal->num1 = 6; cal->num2 = 3; cout << "加法:" << cal->getResult() << endl; delete cal; cal = new Div; cal->num1 = 6; cal->num2 = 3; cout << "除法:" << cal->getResult() << endl; delete cal; } int main() { test2(); system("pause"); return 0; }
使用多态,虽然代码量增加了,但是逻辑却更加明确,只需要关注要实现的操作的本身。