某咖啡店当卖咖啡时,可以根据顾客的要求在其中加入各种配料,咖啡店会根据所加入的配

考试题库2022-08-02  43

问题 某咖啡店当卖咖啡时,可以根据顾客的要求在其中加入各种配料,咖啡店会根据所加入的配料来计算费用。咖啡店所供应的咖啡及配料的种类和价格如下表所示。现采用装饰器(Decorator)模式来实现计算费用的功能,得到如图5-1所示的类图【C++代码】#include<iostream>#include<string>using namespace std;const int ESPRESSO_PRICE=25;const int DRAKROAST_PRICE=20;const int MOCHA_PRICE=10;const int WHIP_PRICE=8;class Beverage{//饮料(1):string description;public:(2)(  ){return description;}(3);};class CondimentDecorator:public Beverage{//配料protected:(4);};class Espresso:public Beverage{//蒸馏咖啡public:Espresso(  ){description="Espresso";}int cost(  ){return ESPRESSO_PRICE;}};class DarkRoast:public Beverage{//深度烘焙咖啡public:DarkRoast(  ){description="DardRoast";}int cost(  ){return DRAKROAST_PRICE;}};class Mocha:public CondimentDecorator{//摩卡public:Mocha(Beverage*beverage){this->beverage=beverage;}string getDescription(  ){return beverage->getDescription(  )+",Mocha";}int cost(  ){return MOCHA_PRICE+beverage->cost(  );}};class Whip:public CondimentDecorator{//奶泡public:Whip(Beverage*beverage){this->beverage=beverage;}string getDescription(  ){return beverage->getDescription(  )+",Whip";}int cost(  ){return WHIP_PRICE+beverage->cost(  );}};int main(  ){Beverage*beverage=new DarkRoast(  );beverage=new Mocha((5));beverage=new Whip((6));cout<<beverage->getDescription(  )<<"¥"<<beverage->cost(  )endl;return 0;}编译运行上述程序,其输出结果为:DarkRoast,Mocha,Whip¥38

选项

答案

解析 (1)protected
(2)virtual string getDescription
(3)virtual int cost()=0
(4)Beverage*beverage
(5)beverage
(6)beverage

本题考查了C++语言的应用能力和装饰设计模式的应用。
第(1)空很明显,是要说明属性description在类Beverage中的类型,应该是私有的、受保护的或公有的,从后面的程序我们可以看出,子类中继承使用了该属性,因此这里只能定义为受保护的,因此第(1)空的答案为protected。
第(2)空处也很明显,是要给出一个函数的定义,并且该函数的函数体是“return description;”,从子类奶泡和摩卡中我们不难发现这个函数应该是getDescription,因此本空的答案为virtual string getDescription。
第(3)空需要结合后面各子类才能发现,在Beverage中还应该定义一个函数cost(),而这个函数在Beverage中并没有实现,因此要定义为纯虚函数,所以第(3)空的答案为virtual int cost()=0。
第(4)空在类CondimentDecorator中,且是该类唯一的一条语句,而他的子类分别是奶泡和摩卡,在奶泡和摩卡这两个类中,都用到了Beverage*beverage,而在使用之前并没有说明,因此这就可以说明,Beverage*beverage是在父类CondimentDecorator中定义的,子类直接继承使用,因此第(4)空的答案为Beverage*beverage。
第(5)和第(6)空在主函数当中,其中第(5)空是要创建一个Mocha对象,应该调用的是类Mocha的构造函数,从类Mocha中,我们可以看出,其构造函数Mocha的参数是一个Beverage类型的对象指针,而在主函数中,开始就定义了一个Beverage类型的对象指针beverage,因此这里只需填写beverage即可。同理第(6)空的答案也是beverage。
转载请注明原文地址:https://www.tihaiku.com/congyezige/2410679.html

最新回复(0)