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

    但愿人长久 千里共婵娟
  • 相关阅读:
    SVG <–> XAML
    Visual Studio 2005 下 ASP.net Web Service SOAP XML 节点的疑惑
    IE 和 Chrome 不能上网,Windows Live Mail 不能发邮件。Firefox可用。解决办法
    c# FileStream和StreamWriter用法
    c# 壓縮與解壓的簡單學習
    c# 文件輸入和輸出主要類說明
    部署Web應用程序
    allowDefinition='MachineToApplication' 错误的解决办法
    Global.asax的16个事件处理过程
    c# 類模板加上自定義內容
  • 原文地址:https://www.cnblogs.com/hellcats/p/4924468.html
Copyright © 2011-2022 走看看