[C++] c++多态性 (父亲 母亲 儿子) →→→→→进入此内容的聊天室

来自 , 2020-05-12, 写在 C++, 查看 102 次.
URL http://www.code666.cn/view/39027dfa
  1. #include <iostream>
  2. using namespace std;
  3. class father
  4. {
  5. public:
  6.         father ( int height );  //父类构造函数带有一个参数height
  7.         virtual ~father() {cout<<"析构父亲...\n";}
  8.         virtual void smart() const {cout<<"父亲很聪明"<<endl;}
  9.         virtual int getheight() const {return itsheight;} //通过成员函数访问私有变量并设置私有变量的值,该函数被说明为虚函数
  10. private:
  11.         int itsheight; //私有成员itsheight
  12. };
  13. father::father ( int height ) :itsheight ( height )     //通过构造函数来设置私有变量的值
  14. {
  15.         cout<<"创建父亲\n";
  16. }
  17. class mother
  18. {
  19. public:
  20.         mother ( bool sex );    //母类的构造函数有一个布尔型参数sex
  21.         virtual ~mother() {cout<<"析构母亲\n";}
  22.         virtual void beautiful() const {cout<<"母亲很漂亮\n";}
  23.         virtual bool getsex() const {return itsex;}     //通过布尔型成员函数访问私有变量并设置私有变量的值,该函数被说明为虚函数
  24. private:
  25.         bool itsex;     //私有布尔变量itsex
  26. };
  27. mother::mother ( bool sex ) :itsex ( sex )      //定义母类的布尔型构造函数sex并设置私有成员的值
  28. {
  29.         cout<<"创建母亲\n";
  30. }
  31. class son:public father,public mother //子类分别继承母类和父类,继承权限为公有
  32. {
  33. public:
  34.         ~son() {cout<<"析构小儿子..."<<endl;}
  35.         son ( int,bool,long );  //子类的构造函数带有三个参数,类型为int,bool和long。
  36.         virtual long getnum() const     //通过long型成员函数getnum访问并返回私有变量num的值。
  37.         {
  38.                 return num;
  39.         }
  40. private:
  41.         long num;
  42. };
  43. son::son ( int height,bool sex,long number ) :father ( height ),mother ( sex ),
  44.                 num ( number )          //子类在构造函数的同时进行初始化,初始化的顺序由程序员指定,这里是首先初始化父类height参数,然后初始化母类的sex参数,最后初始化子类的number参数。
  45. {                   //所有这些初始化工作完成后
  46.         cout<<"创建小儿子\n";      //方才执行son的构造函数
  47. }
  48. int main()
  49. {
  50.         son*ps=new son ( 5,true,3 );    //在堆中创建一个son类对象并初始化构造函数的三个参数,同时声明一个son类的指针使其指向这个新建的堆
  51.         ps->beautiful();        //用该指针访问从母类继承来的虚函数
  52.         ps->smart();            //用该指针访问从父类继承来的虚函数
  53.         cout<<"\n小儿子有"<<ps->getheight();        //用该指针访问从父类继承来的虚函数
  54.         cout<<"英尺高\n";
  55.         if ( ps->getsex() )                     //用该指针访问从母类继承来的布尔函数
  56.                 cout<<"性别:男";
  57.         else
  58.                 cout<<"性别:女";
  59.         cout<<"\n在家排行:第"<<ps->getnum() <<endl;      //用该指针访问子类的getnum函数
  60.         delete ps;                                                              //删除这个指向son类对象的指针
  61.         system ( "pause" );
  62.         return 0;
  63. }
  64.  

回复 "c++多态性 (父亲 母亲 儿子)"

这儿你可以回复上面这条便签

captcha