• c++ 多态的


    1. #include
    2. #include
    3. using namespace std;
    4. //含有纯虚函数为抽象类,无法实例化
    5. class AbstractDrinking
    6. {
    7. public:
    8. //煮水
    9. virtual void Boil() = 0;
    10. //冲泡
    11. virtual void Brew() = 0;
    12. //导入杯子中
    13. virtual void PourInCup() = 0;
    14. //加入辅料
    15. virtual void PutSomething() = 0;
    16. //制作,子类总会调用子类的具体方法
    17. void makeDrink()
    18. {
    19. Boil();
    20. Brew();
    21. PourInCup();
    22. PutSomething();
    23. }
    24. };
    25. //制作coffee
    26. class Coffee : public AbstractDrinking
    27. {
    28. public:
    29. //煮水
    30. virtual void Boil()
    31. {
    32. cout << "煮制做咖啡的水" << endl;
    33. }
    34. //冲泡
    35. virtual void Brew()
    36. {
    37. cout << "冲泡咖啡" << endl;
    38. }
    39. //导入杯子中
    40. virtual void PourInCup()
    41. {
    42. cout << "倒水入杯子" << endl;
    43. }
    44. //加入辅料
    45. virtual void PutSomething()
    46. {
    47. cout << "加糖" << endl;
    48. }
    49. };
    50. //制作Tea
    51. class Tea : public AbstractDrinking
    52. {
    53. public:
    54. //煮水
    55. virtual void Boil()
    56. {
    57. cout << "煮制做茶的水" << endl;
    58. }
    59. //冲泡
    60. virtual void Brew()
    61. {
    62. cout << "冲泡茶叶" << endl;
    63. }
    64. //导入杯子中
    65. virtual void PourInCup()
    66. {
    67. cout << "倒水入杯子" << endl;
    68. }
    69. //加入辅料
    70. virtual void PutSomething()
    71. {
    72. cout << "不加辅料" << endl;
    73. }
    74. };
    75. void doWork(AbstractDrinking* a)
    76. {
    77. a->makeDrink();
    78. delete a;
    79. };
    80. void test()
    81. {
    82. doWork(new Coffee);
    83. cout << "--------------" << endl;
    84. doWork(new Tea);
    85. }
    86. void main()
    87. {
    88. test();
    89. }

  • 相关阅读:
    博客与AI
    JS中的 typeof 针对各种类型的返回值 以及typeof历史遗留问题
    FFMPEG centos 安装指南
    pycharm 用MD文件制作流程图
    Docker02基本管理
    编译原理实验-词法分析
    linux内核中的SPI
    @Import :Spring Bean模块装配的艺术
    基于Xml方式Bean的配置-Bean的延时加载
    python数据分析之Pandas库(一)
  • 原文地址:https://blog.csdn.net/lengyue1084/article/details/133173692