子類和父類的構造函數


子類與父類的構造函數  

2008-11-07 18:13:17|  分類: c/c++ |  標簽: |字號 訂閱

 
 

先看下面的例子:
    #include <iostream.h>
    class animal
    {
    public:
         animal(int height, int weight)
         {
             cout<<"animal construct"<<endl;
         }
         ~animal()
         {
             cout<<"animal destruct"<<endl;
         }
         void eat()
         {
             cout<<"animal eat"<<endl;
         }
         void sleep()
         {
             cout<<"animal sleep"<<endl;
         }
         void breathe()
         {
             cout<<"animal breathe"<<endl;
         }
    };
    class fish:public animal
    {
    public:
         fish()
         {
             cout<<"fish construct"<<endl;
         }
         ~fish()
         {
             cout<<"fish destruct"<<endl;
         }
    };
    void main()
    {
         fish fh;
    }

當我們構造fish子類的對象fh時,它需要先構造anima父l類的對象,調用anima父l類的默認構造函數(即不帶參數的構造函數),而在我們的程序中,animal類只有一個帶參數的構造函數,在編譯時,編譯器會自動產生一個不帶參數的animal父類構造函數作為默認的構造函數。

在子類構造函數中想要調用父類有參數的構造函數(或子類要向父類的構造函數傳遞參數)時,就必須顯式的指明需要調用的是哪一個父類構造函數。具體方法是:子類構造函數應當這樣聲明  子類名::子類名(參數):父類名(參數);
可以采用如下例子所示的方式,在構造子類時,顯式地去調用父類的帶參數的構造函數,而父類無參數的構造函數則不再調用。

#include <iostream.h>
    class animal
    {
    public:
        animal(int height, int weight)
        {
            cout<<"animal construct"<<endl;
        }
        …
    };
    class fish:public animal
    {
    public:
        fish():animal(400,300)
        {
            cout<<"fish construct"<<endl;
        }
        …
    };
    void main()
    {
        fish fh;
    }

此外還可以使用this指針來調用父類有參數的構造函數,具體做法如下代碼:

#include <iostream.h>
    class animal
    {
    public:
        animal(int height, int weight)
        {
            cout<<"animal construct"<<endl;
        }
        …
    };
    class fish:public animal
    {
    public:
        fish()
        { 
            this->animal ::animal (400,300);
        }
        …
    };
    void main()
    {
        fish fh;
    }

這在子類化一些抽象類的時候很有幫助,今天一整天的收獲還不錯。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM