多态计算器

tech2022-08-15  141

#include<iostream> using namespace std; //普通实现 class Calculate { public: int getResult(string oper) { if (oper == "+") { return m_Num1 + m_Num2; } else if (oper == "-") { return m_Num1 - m_Num2; } else if (oper == "*") { return m_Num1 * m_Num2; } else if(oper == "/") { return m_Num1 / m_Num2; } } public: int m_Num1; int m_Num2; }; //普通实现验证 void test01() { Calculate c; c.m_Num1 = 10; c.m_Num2 = 10; cout << c.m_Num1 << "+" << c.m_Num2 << "=" << c.getResult("+") << endl; cout << c.m_Num1 << "-" << c.m_Num2 << "=" << c.getResult("-") << endl; cout << c.m_Num1 << "*" << c.m_Num2 << "=" << c.getResult("*") << endl; cout << c.m_Num1 << "/" << c.m_Num2 << "=" << c.getResult("/") << endl; } //多态实现 //抽象计算器类 //1、结构清晰 2、可读性强 3、利于前期和后期的扩展和维护 class AbstractCalculate { public: virtual int getResult() { return 0; } public: int m_Num1; int m_Num2; }; //加法计算器 class AddCalculate :public AbstractCalculate { public: int getResult() { return m_Num1 + m_Num2; } }; //减法计算器 class SubCalculate :public AbstractCalculate { public: int getResult() { return m_Num1 - m_Num2; } }; //乘法计算器 class MulCalculate :public AbstractCalculate { public: int getResult() { return m_Num1 * m_Num2; } }; //除法计算器 class DivCalculate :public AbstractCalculate { public: int getResult() { return m_Num1 / m_Num2; } }; //多态验证 void test02() { AbstractCalculate * abc = new AddCalculate; abc->m_Num1 = 10; abc->m_Num2 = 10; cout << abc->m_Num1 << "+" << abc->m_Num2 << "=" << abc->getResult() << endl; delete abc; abc = new SubCalculate; abc->m_Num1 = 10; abc->m_Num2 = 10; cout << abc->m_Num1 << "-" << abc->m_Num2 << "=" << abc->getResult() << endl; delete abc; abc = new MulCalculate; abc->m_Num1 = 10; abc->m_Num2 = 10; cout << abc->m_Num1 << "*" << abc->m_Num2 << "=" << abc->getResult() << endl; delete abc; abc = new DivCalculate; abc->m_Num1 = 10; abc->m_Num2 = 10; cout << abc->m_Num1 << "/" << abc->m_Num2 << "=" << abc->getResult() << endl; delete abc; } int main() { //test01(); test02(); system("pause"); return 0; }
最新回复(0)