C++中多态(polymorphism)有以下三个前提条件:
#include <iostream> using namespace std; class CTradesPerson{ // base class public : virtual void sayHi(){ cout<<"Just hi."<<endl;} }; class CTinker : public CTradesPerson{// drived class 1 public : virtual void sayHi(){cout<<"Hi, I tinker."<<endl;} }; class CTailor : public CTradesPerson{// drived class 2 public: virtual void sayHi(){ cout<<"Hi, i tailor"<<endl;} }; int main(){ CTradesPerson* p; // pointer to base class int which ; // prompt user for a number //*** 1 ==CTadesPerson // 2 ==CTinker // 3 ==CTailor do{ cout <<"1 == CTradesPerson, 2 == CTinker, 3 == CTailor"<<endl; cin >>which; }while(which<1||which>3); //set pointer p depending on user choice switch(which){ case 1: p = new CTradesPerson; break; case 2: p = new CTinker; break; case 3: p = new CTailor; break; } // invoke the sayHi method via the pointer p->sayHi(); // ***runt-time binding in effect delete p; // *** free the dymanicall y allocated storage return 0; }
程序清单的程序阐明了多态及其三个前提条件:
在该程序的某次运行过程中,我们输入数据1,就会得到如下结果:
当我们输入数据3, 就会得到如下结果:
关于Program Language更多讨论与交流,敬请关注本博客和新浪微博songzi_tea.
原文:http://blog.csdn.net/songzitea/article/details/40659327