#include<iostream>
using namespace std;//制作饮品的大致流程都为:
//煮水-----冲泡-----倒入杯中----加入辅料//本案例利用多态技术,提供抽象类制作饮品基类,提供子类制作茶叶和咖啡class AbstractDrinking {public://煮水//冲水//倒入杯中//加入辅料virtual void Boil() = 0;virtual void Brew() = 0;virtual void PourInCup() = 0;virtual void PutSomething() = 0;//接下来制作饮品void makeDrink(){Boil();Brew();PourInCup();PutSomething();}};//制作咖啡
class Coffee :public AbstractDrinking
{//重写父类的虚函数
public:virtual void Boil(){cout << "煮矿泉水" << endl;}virtual void Brew(){cout << "冲泡咖啡" << endl;}virtual void PourInCup(){cout << "倒入杯中1" << endl;}virtual void PutSomething(){cout << "加入糖和牛奶" << endl;}};//制作茶叶
class Tea :public AbstractDrinking
{//重写父类的虚函数
public:virtual void Boil(){cout << "煮泰山泉水" << endl;}virtual void Brew(){cout << "冲泡茶叶" << endl;}virtual void PourInCup(){cout << "倒入杯中2" << endl;}virtual void PutSomething(){cout << "加入枸杞" << endl;}};void doWork(AbstractDrinking *drink)//使用父类指针指向子类对象 AbstractDrinking *drink=new Coffee
{drink->makeDrink();delete drink;//释放
}void testDoWork()
{doWork(new Coffee);//一个接口多种形态cout << "-------------------" << endl;doWork(new Tea);
}int main()
{testDoWork();}
结果: