1. 首页
  2. 课程学习
  3. C++/C
  4. 动态联编与多态性(动态联编例子.cpp)

动态联编与多态性(动态联编例子.cpp)

上传者: 2022-07-05 17:20:56上传 .CPP文件 914.00 Bytes 热度 19次

#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

用户评论