程序:
#pragma warning(disable:4996)
#define _CRT_SECURE_NO_WARNINGS 1
//2022年10月19日19:29:49
#include <iostream>
using namespace std;
class Drink
{
public:
//煮水
virtual void Boil() = 0;
//冲泡
virtual void Brew() = 0;
//倒入杯中
virtual void PourInCup() = 0;
//加点辅料
virtual void addSonm() = 0;
//模板方法,把调用函数顺序确定下来
void func()
{
Boil();
Brew();
PourInCup();
addSonm();
}
};
class Coffee: public Drink
{
//煮水
virtual void Boil()
{
cout << "煮点露水" << endl;
}
//冲泡
virtual void Brew()
{
cout << "冲泡" << endl;
}
//倒入杯中
virtual void PourInCup()
{
cout << "倒入盆中" << endl;
}
//加点辅料
virtual void addSonm()
{
cout << "加点大蒜" << endl;
}
};
class Tea: public Drink
{
//煮水
virtual void Boil()
{
cout << "煮水自来水" << endl;
}
//冲泡
virtual void Brew()
{
cout << "铁观音" << endl;
}
//倒入杯中
virtual void PourInCup()
{
cout << "倒入碗中" << endl;
}
//加点辅料
virtual void addSonm()
{
cout << "加点酱油" << endl;
}
};
void test()
{
Drink *dr = NULL;
dr = new Coffee;
dr->func();
delete dr;
dr = new Tea;
dr->func();
delete dr;
dr = NULL;
}
int main()
{
test();
system("pause");
return EXIT_SUCCESS;
}
输出结果:
煮点露水
冲泡
倒入盆中
加点大蒜
煮水自来水
铁观音
倒入碗中
加点酱油
请按任意键继续. . .
参考资料
参考资料来源于黑马程序员等
原文链接: https://www.cnblogs.com/codemagiciant/p/17149725.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/319874
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!