C++語言類成員變量初始化總結

 共有5種方法。

第1種,在無參數的構造函數中初始化;

第2種,帶參數的構造函數中初始化;

第3種,直接給成員變量賦值;

第4種,調用成員函數來初始化成員變量;

第5種,用this指針;

分別敘述。

方法一

  1. class animal 
  2. public: 
  3.     int a,b; 
  4.     animal(); 
  5. }; 
  6. animal::animal() 
  7.  
  8.     a=5
  9.     b=3

方法二

  1. class animal 
  2. public: 
  3.     int a,b; 
  4.     animal(int x,int y);//構造函數,有參數 
  5. }; 
  6. animal::animal(int x,int y) 
  7.     a=x
  8.     b=y

方法三:

  1. class animal 
  2. public: 
  3.     int a,b; 
  4. }; 
  5. void main() 
  6.     animal cat; 
  7.     cat.a=5;//直接給成員變量賦值 
  8.  
  9.     cat.b=3
  10.     cout<<cat.a<<endl<<cat.b<<endl

方法四:

  1. class animal 
  2. public: 
  3.     int a,b; 
  4.     void init(int x,int y); 
  5. }; 
  6. void animal::init(int x,int y) 
  7.     a=x
  8.     b=y
  9.  
  10. void main() 
  11.     animal cat; 
  12.     cat.init(5,3);//調用成員函數的方法給成員變量初始化 
  13.  
  14.     cout<<cat.a<<endl<<cat.b<<endl

方法五:

  1. class animal 
  2. public: 
  3.     int a,b; 
  4.     void init(int x,int y); 
  5. }; 
  6. void animal::init(int a,int b) 
  7.     this->aa=a;//當形參變量名與成員變量名發生衝突時,用this指針區分想對哪個變量賦值 
  8.  
  9.     this->bb=b; 

針對不同的變量類型,在選擇初始化方法時,有不同的優先順序。總結如下:

普通的變量

一般不考慮啥效率的情況下 可以在構造函數中進行賦值。考慮一下效率的可以再構造函數的初始化列表中進行。

  1. class CA 
  2. public: 
  3.    int data; 
  4.    public: 
  5.    CA(); 
  6. }; 
  7. CA::CA():data(0)//……#1……初始化列表方式 
  8. //data = 0;//……#1……賦值方式 
  9. }; 

static 靜態變量:
static變量屬於類所有,而不屬於類的對象,因此不管類被實例化了多少個對象,該變量都只有一個。在這種性質上理解,有點類似於全局變量的唯一性。

  1. class CA 
  2. public: 
  3. static int sum; 
  4. public: 
  5. CA(); 
  6. }; 
  7. int CA::sum=0;//……#2……類外進行初始化 

const 常量變量: const常量需要在聲明的時候即初始化。因此需要在變量創建的時候進行初始化。必須採用在構造函數的初始化列表中進行。

  1. class CA 
  2. public: 
  3. const int max; 
  4. public: 
  5. CA(); 
  6. }; 
  7. CA::CA():max(100) 
  8. …… 

Reference 引用型變量: 引用型變量和const變量類似。需要在創建的時候即進行初始化。也是必須在初始化列表中進行。

 

  1. class CA 
  2. public: 
  3. int init; 
  4. int& counter;  
  5. …… 
  6. public: 
  7. CA(); 
  8. …… 
  9. }; 
  10. CA::CA():counter(init) 
  11. …… 

const static integral 變量: 對於既是const又是static 而且還是整形變量,C++是給予特權的。可以直接在類的定義中初始化。short可以,但float的不可以哦。

 

  1. class CA 
  2. public: 
  3. //static const float fmin = 0.0;// only static const integral data members can be initialized within a class 
  4. const static int nmin = 0
  5. public: 
  6. }; 

總結起來,可以初始化的情況有如下四個地方: 1、在類的定義中進行的,只有const 且 static 且 integral 的變量。 2、在類的構造函數初始化列表中, 包括普通變量,const常量(不包含第一種情況)和Reference變量。 3、在類的定義之外初始化的,包括static變量。因爲它是屬於類的唯一變量。 4、普通的變量可以在構造函數的內部,通過賦值方式進行。當然這樣效率不高。 5.const數據成員(非static)必須在構造函數的初始化列表中初始化。 6.數組成員是不能在初始化列表裏初始化的。 7.const static 和static const是一樣的,這樣的變量可以直接在類定義中初始化,也可以在類外。 說明了一個問題:C++裏面是不能定義常量數組的!因爲5和6的矛盾。 類對象的構造順序是這樣的: 1.分配內存,調用構造函數時,隱式/顯示的初始化各數據成員 2.進入構造函數後在構造函數中執行一般計算

 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章