前面我們學習了C++使用初始化列表的方式來初始化字段的方法:
http://www.49028c.com/kaifa/c/336530.html
這一節的原理和前面的差不多。
在C++的構造函數中,子類繼承父類,那么,在創建一個子類成員時,可以同時向父類或者子類的構造函數進行傳參,實現方法如下:
寫一個例子:mul_argc.c
#include <iostream>#include <cstring>using namespace std ; //英雄聯盟類 class Hero{ private : int blood ; string name ; public : Hero(int blood = 100, string name = "man wang") { this->blood = blood ; this->name = name ; } ~Hero() { if(this->blood < 0){ cout << "Hero blood error!/n" << endl ; return ; } cout << "Hero name is:" << this->name << endl ; cout << "Hero blood is :" << this->blood << endl ; } }; //德瑪類,繼承于英雄類 class Dema : public Hero{ private : int blood ; string name ; public : Dema(int blood , string name); ~Dema();};//在實現子類的構造函數時,可以同時向父類的構造函數傳參//例如這個例子的 : Hero(58,JS),相當于向父類的構造函數傳參//當然,子類也可以給本類的的成員傳參Dema::Dema(int blood , string name) : Hero(89 , "JS") , blood(58) , name("dema"){ this->name = name ; this->blood = blood ; }Dema::~Dema(){ if(this->name != "dema"){ cout << "This Hero are no dema!" << endl; return ; } if(this->blood < 0){ cout << "Dema blood error!/n" << endl ; return ; } cout << "Dmea name is:" << this->name << endl ; cout << "Dema blood is :" << this->blood << endl ; }int main(int argc , char **argv){ Dema player1(79,"dema"); return 0 ;}
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對VEVB武林網的支持。
新聞熱點
疑難解答