虚函数总结实例

#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");
}

posted @ 2015-10-30 21:54  Lucky-小王子  阅读(253)  评论(0编辑  收藏  举报