当前位置:   article > 正文

C++简单实现多态案例-制作饮品

C++简单实现多态案例-制作饮品

代码示例如下:

  1. #include<iostream>
  2. using namespace std;
  3. class AbstractDrinking
  4. {
  5. public:
  6. virtual void Soil() = 0;//第一步、煮开水
  7. virtual void Brew() = 0;//第二步、冲泡
  8. virtual void PourInCup() = 0;//第三步、倒入杯中
  9. virtual void AddSomething() = 0;//第四步、加入辅料
  10. };
  11. void makeDrink(AbstractDrinking* abd)
  12. {
  13. abd->Soil();
  14. abd->Brew();
  15. abd->PourInCup();
  16. abd->AddSomething();
  17. }
  18. class Coffee : public AbstractDrinking
  19. {
  20. public:
  21. void Soil()
  22. {
  23. cout << "煮咖啡" << endl << "第一步、煮沸百岁山" << endl;
  24. }
  25. void Brew()
  26. {
  27. cout << "第二步、冲泡咖啡" << endl;
  28. }
  29. void PourInCup()
  30. {
  31. cout << "第三步、倒入杯中" << endl;
  32. }
  33. void AddSomething()
  34. {
  35. cout << "第四步、加入糖和牛奶" << endl << endl;
  36. }
  37. };
  38. class Tea : public AbstractDrinking
  39. {
  40. void Soil()
  41. {
  42. cout << "泡茶叶" << endl << "第一步、煮沸怡宝" << endl;
  43. }
  44. void Brew()
  45. {
  46. cout << "第二步、冲泡茶叶" << endl;
  47. }
  48. void PourInCup()
  49. {
  50. cout << "第三步、倒入杯中" << endl;
  51. }
  52. void AddSomething()
  53. {
  54. cout << "第四步、加入枸杞" << endl;
  55. }
  56. };
  57. int main() {
  58. AbstractDrinking* cof = new Coffee;
  59. AbstractDrinking* tea = new Tea;
  60. makeDrink(cof);
  61. makeDrink(tea);
  62. }

结果如下:

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/码创造者/article/detail/982987?site
推荐阅读
相关标签
  

闽ICP备14008679号