程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> VC >> vc教程 >> 在子類中調用父類的帶參數的構造函數

在子類中調用父類的帶參數的構造函數

編輯:vc教程

  下面我們修改一下animal類的構造函數,增加兩個參數height和weight,分別表示動物的高度和重量。代碼如例2-13所示。

  例2-13

  #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時,它需要先構造animal類的對象,調用animal類的默認構造函數(即不帶參數的構造函數),而在我們的程序中,animal類只有一個帶參數的構造函數,在編譯時,因找不到animal類的默認構造函數而出錯。

  因此,在構造fish類的對象時(調用fish類的構造函數時),要想辦法去調用animal類的帶參數的構造函數,那麼,我們如何在子類中向父類的構造函數傳遞參數呢?可以采用如例2-14所示的方式,在構造子類時,顯式地去調用父類的帶參數的構造函數。

  例2-14

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

  注意程序中以粗體顯示的代碼。在fish類的構造函數後,加一個冒號(:),然後加上父類的帶參數的構造函數。這樣,在子類的構造函數被調用時,系統就會去調用父類的帶參數的構造函數去構造對象。這種初始化方式,還常用來對類中的常量(const)成員進行初始化,如下面的代碼所示:

  class point
  {
  public:
     point():x(0),y(0)
  private:
     const int x;
     const int y;
  };

  當然,類中普通的成員變量也可以采取此種方式進行初始化,然而,這就沒有必要了。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved