开闭原则是一种开发原则,表述为
    对拓展进行开放,对修改进行关闭。
    也就是对拓展功能进行开放,但是修改代码时不被允许,源代码具有拓展性,那么就可以直接进行拓展,不建议修改源码。
    例如下面的计算机案例

    1. #include <iostream>
    2. #include <string>
    3. using namespace std;
    4. class Calculator {
    5. public:
    6. int getResult(string optr) {
    7. if (optr == "+") {
    8. return m_Num1 + m_Num2;
    9. }
    10. else if (optr == "-") {
    11. return m_Num1 - m_Num2;
    12. }
    13. else if (optr == "*") {
    14. return m_Num1 * m_Num2;
    15. }
    16. else return 0;
    17. }
    18. int m_Num1;
    19. int m_Num2;
    20. };
    21. void example() {
    22. Calculator c1;
    23. c1.m_Num1 = 2;
    24. c1.m_Num2 = 3;
    25. cout << c1.m_Num1 << "+" << c1.m_Num2 << "=" << c1.getResult("+") << endl;
    26. }
    27. int main() {
    28. example();
    29. return 0;
    30. }

    上面的案例中,每次增加功能时,都必须要更改类。而且对源码的更改涉及到数据结构的变化,不符合开闭原则。
    那么就需要用多态来实现将计算机作为总体抽象出来,然后再具体添加功能类。

    1. #include <iostream>
    2. #include <string>
    3. using namespace std;
    4. class AbstractCalculator {
    5. public:
    6. virtual int getResult() {
    7. return 0;
    8. }
    9. int m_Num1;
    10. int m_Num2;
    11. };
    12. class Add :public AbstractCalculator {
    13. public:
    14. int getResult() {
    15. return m_Num1 + m_Num2;
    16. }
    17. };
    18. class miu :public AbstractCalculator {
    19. public:
    20. int getResult() {
    21. return m_Num1 - m_Num2;
    22. }
    23. };
    24. class mul :public AbstractCalculator {
    25. public:
    26. int getResult() {
    27. return m_Num1 * m_Num2;
    28. }
    29. };
    30. void example() {
    31. AbstractCalculator *Calc = new Add;
    32. Calc->m_Num1 = 10;
    33. Calc->m_Num2 = 20;
    34. cout << Calc->m_Num1 << "+" << Calc->m_Num2 << "=" << Calc->getResult()<< endl;
    35. delete Calc;
    36. Calc = new miu;
    37. Calc->m_Num1 = 40;
    38. Calc->m_Num2 = 10;
    39. cout << Calc->m_Num1 << "-" << Calc->m_Num2 << "=" << Calc->getResult() << endl;
    40. delete Calc;
    41. Calc = new mul;
    42. Calc->m_Num1 = 4;
    43. Calc->m_Num2 = 5;
    44. cout << Calc->m_Num1 << "*" << Calc->m_Num2 << "=" << Calc->getResult() << endl;
    45. delete Calc;
    46. }
    47. int main() {
    48. example();
    49. return 0;
    50. }

    虽然再整体上代码量更高,但是在实际开发场景中,拓展性可读性都将大大增强。
    总结:C++开发提倡利用多态设计程序架构,因为多态优点很多