c++多态的一个例子

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 #define vi virtual
 4 class abstractdrink{
 5     public:
 6         //煮水 
 7         vi void Boil() = 0;
 8         //冲泡
 9         vi void Brew() = 0;
10         //倒入杯中
11         vi void Pourincup() = 0;
12         //添加辅料
13         vi void Addsomething() = 0;
14         void makeDrink()
15         {
16             Boil();
17             Brew();
18             Pourincup();
19             Addsomething();
20         } 
21 };
22 
23 class Coffee:public abstractdrink{
24         void Boil() {
25             cout << "煮开水" << endl; 
26         }
27         //冲泡
28          void Brew() {
29              cout << "冲泡咖啡" << endl; 
30          }
31         //倒入杯中
32          void Pourincup() {
33              cout << "倒入杯中" << endl;
34          }
35         //添加辅料
36          void Addsomething(){
37              cout << "添加牛奶和糖" << endl; 
38          }
39 };
40 
41 class Tea:public abstractdrink{
42         void Boil() {
43             cout << "煮开水" << endl; 
44         }
45         //冲泡
46          void Brew() {
47              cout << "冲泡茶叶" << endl; 
48          }
49         //倒入杯中
50          void Pourincup() {
51              cout << "倒入杯中" << endl;
52          }
53         //添加辅料
54          void Addsomething(){
55              cout << "添加枸杞" << endl; 
56          }
57 };
58 void dowork(abstractdrink *abs)
59 {
60     abs->makeDrink();
61     delete abs;
62 }
63 void test()
64 {
65     dowork(new Coffee);
66     cout << "---------->" << endl;
67     dowork(new Tea);
68 } 
69 
70 int main()
71 {
72     test();
73     return 0;
74 }

 

posted @ 2019-09-11 19:38  ChunhaoMo  阅读(322)  评论(0编辑  收藏  举报