zoukankan      html  css  js  c++  java
  • 虚函数总结实例

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

    但愿人长久 千里共婵娟
  • 相关阅读:
    使用vue做项目时,刷新页面,原本应该隐藏的东西闪一下
    input type="file" 上传文件的一些使用
    vue强制重新渲染
    元素focus页面不滚动不定位的JS处理
    js使用案例
    js使用setInterval简单实现一个时钟
    js日期封装方法
    scss简单使用总结
    JavaScript的内置对象(Global对象)
    JavaScript—Date对象详情
  • 原文地址:https://www.cnblogs.com/hellcats/p/4924468.html
Copyright © 2011-2022 走看看