首页 > 其他 > 详细

虚函数总结实例

时间:2015-10-30 22:51:15      阅读:213      评论:0      收藏:0      [点我收藏+]
#include <iostream>
using namespace std ;
class animal  
{  
public:  
    animal()
    {
        cout <<"animal构造函数"<<endl;
    }
       void sleep()  
       {  
              cout<<"animal sleep"<<endl;  
       }  
      virtual   void breathe()  
       {  
              cout<<"animal breathe"<<endl;  
       }  
       ~animal ()
       {
           cout <<"animal析构函数"<<endl;
       }
};  
class fish:public animal  
{  
public: 
    fish ()
    {
          cout <<"fish构造函数"<<endl;
    }
       void sleep()  
       {  
              cout<<"fish sleep"<<endl;  
       }  
      void breathe()  
       {  
              cout<<"fish bubble"<<endl;  
       }  
          ~fish ()
       {
           cout <<"fish析构函数"<<endl;
       }
};  
void main()  
{  
       fish fh;  

       animal *pAn=&fh; // 隐式类型转换 指针不调用构造函数 一旦某个函数在基类中声明为virtual,
                        //那么在所有的派生类中该函数都是virtual,而不需要再显式地声明为virtual。
       /*若是animal类里面的breathe() 不是虚函数则,打印的是animal breathe*/
       /*若是animal类里面的breathe() 是虚函数则,打印的是fish bubble*/
       /*若是animal类里面的sleep() 不是虚函数则,fish类继承了animal,sleep()为虚函数.则打印animal sleep*/
        pAn->breathe();  //fish bubble
        pAn ->sleep();//animal sleep

        animal *ani= new fish;//因为有new创建了一个fish对象,因此打印构造函数。
        ani->breathe() ;//fish bubble
        ani->sleep ();  //animal sleep

    fish *fh1 =new fish();
    fh1->sleep ();//fish sleep
    animal *ani1=(animal*)fh1;
    ani1 ->breathe ();  //fish bubble
    ani1 ->sleep();    //animal sleep

    ((fish*)(ani1))->breathe ();//fish bubble
    ((fish*)(ani1))->sleep  ();////fish sleep
    ani ->sleep ();    //animal sleep

    animal *ani2=new animal ();
    ani2->breathe ();//animal breathe
    ani2->sleep ();//animal sleep

    fish *fh2=(fish*)ani2;

    fh2->breathe ();//animal breathe  虚子函数没有变
    fh2->sleep ();//fish sleep  

    ((animal*)(fh2))->breathe ();//animal breathe
    ((animal*)(fh2))->sleep ();//animal sleep

            system("pause");
}

技术分享

虚函数总结实例

原文:http://www.cnblogs.com/hellcats/p/4924468.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!