班上一位同学参加了软考,问我这样一道题目,结果出乎我的意料:
class SalesTicket {
public:
virtual void printTicket(){cout<<"\n这里是正文"<<endl;}
};
class Decorator:public SalesTicket{
SalesTicket *ticket;
public:
Decorator(SalesTicket *t){ticket=t;}
void printTicket(){
if(ticket!=NULL){
ticket->printTicket();}
}
};
class HeadDecorator:public Decorator{
public:
HeadDecorator(SalesTicket *t):Decorator(t){}
void printTicket(){
cout<<"\n这里是票据的抬头"<<endl;
Decorator::printTicket();
}
};
class FootDecorator:public Decorator{
public:
FootDecorator(SalesTicket *t):Decorator(t){}
void printTicket(){
Decorator::printTicket();
cout<<"\n这里是票据的脚注"<<endl;
}
};
void main(void)
{
SalesTicket t;
FootDecorator f(&t);
HeadDecorator h(&f);
h.printTicket();
cout<<"\n------------------------"<<endl;
FootDecorator a(NULL);
HeadDecorator b(&a);
b.printTicket();
}
有兴趣的可以做一下啊,使你功力倍增
评论