动态联编与多态性(动态联编例子.cpp)
#include
class Cannonball{//礼花炮弹
public:
voidignite() //引爆
{
disperse(); //动态联编
}
virtualvoid disperse(){}//炸开
};
class YellowCannonball:public Cannonball{ //黄色礼花炮弹
public:
virtualvoid disperse()//炸开
{
cout<<"Theyellow flower dispersing"< } }; class RedCannonball:public Cannonball{ //红色礼花炮弹 public: virtualvoid disperse()//炸开 { cout<<"Thered flower dispersing"< } }; class GreenCannonball:public Cannonball{ //绿色礼花炮弹 public: virtualvoid disperse()//炸开 { cout<<"Thegreen flower dispersing"< } }; void salute(Cannonball *p)//礼炮函数 { //p->disperse();//动态联编 p->ignite(); //静态联编 } int main() { RedCannonball ObjRed; GreenCannonball ObjGreen; YellowCannonball ObjYellow; salute(&ObjRed); salute(&ObjGreen); salute(&ObjYellow); return0; } 程序执行结果: Thered flower dispersing Thegreen flower dispersing Theyellow flower dispersing