1 //多态案例 -计算器类(普通写法 和 多态写法) 2 3 #include <iostream> 4 #include <string> 5 using namespace std; 6 7 //普通实现 8 class Calualtor 9 { 10 public: 11 12 int getResult(string oper) 13 { 14 if (oper == "+") 15 { 16 return m_Num1 + m_Num2; 17 } 18 else if (oper == "-") 19 { 20 return m_Num1 - m_Num2; 21 } 22 else if (oper == "*") 23 { 24 return m_Num1 * m_Num2; 25 } 26 //如果想扩展新的功能,需要修改源码 27 //在真实的开发中 提倡 开闭原则 28 //开闭原则:对扩展进行开放 对修改进行关闭 29 } 30 31 32 int m_Num1; //操作数1 33 int m_Num2; //操作数2 34 }; 35 36 void test01() 37 { 38 //创建计算器的对象 39 Calualtor c; 40 c.m_Num1 = 10; 41 c.m_Num2 = 10; 42 43 cout << c.m_Num1 << "+" << c.m_Num2 << "=" << c.getResult("+") << endl; 44 45 cout << c.m_Num1 << "-" << c.m_Num2 << "=" << c.getResult("-") << endl; 46 47 cout << c.m_Num1 << "*" << c.m_Num2 << "=" << c.getResult("*") << endl; 48 } 49 50 51 //利用多态实现计算器 52 //多态好处: 53 //1.组织结构清晰 54 //2.可读性强 55 //3.对于前期和后期扩展以及维护性高 56 57 58 //实现计算器的抽象类 59 class AbstractCalculator 60 { 61 public: 62 63 virtual int getResult() 64 { 65 return 0; 66 } 67 68 int m_Num1; 69 int m_Num2; 70 }; 71 72 //加法计算器 73 class AddCalculator : public AbstractCalculator 74 { 75 76 public: 77 virtual int getResult() 78 { 79 return m_Num1 + m_Num2; 80 } 81 }; 82 83 //减法计算器 84 class SubCalculator : public AbstractCalculator 85 { 86 87 public: 88 virtual int getResult() 89 { 90 return m_Num1 - m_Num2; 91 } 92 }; 93 //乘法计算器 94 class MulCalculator : public AbstractCalculator 95 { 96 97 public: 98 virtual int getResult() 99 { 100 return m_Num1 * m_Num2; 101 } 102 }; 103 104 105 void test02() 106 { 107 //多态使用条件 108 109 //父类指针或者引用指向子类对象 110 //加法运算 111 AbstractCalculator* abc = new AddCalculator; 112 abc->m_Num1 = 10; 113 abc->m_Num2 = 20; 114 cout << "多态计算器" << endl; 115 cout << abc->m_Num1 << "+" << abc->m_Num2 << "=" << abc->getResult() << endl; 116 117 //用完后销毁 118 delete abc; 119 120 //减法运算 121 abc = new SubCalculator; 122 abc->m_Num1 = 100; 123 abc->m_Num2 = 101; 124 cout << abc->m_Num1 << "-" << abc->m_Num2 << "=" << abc->getResult() << endl; 125 delete abc; 126 127 abc = new MulCalculator; 128 abc->m_Num1 = 12; 129 abc->m_Num2 = 10; 130 cout << abc->m_Num1 << "*" << abc->m_Num2 << "=" << abc->getResult() << endl; 131 132 delete abc; 133 } 134 135 int main() 136 { 137 138 test01(); 139 140 test02(); 141 142 system("pause"); 143 144 return 0; 145 146 }