本文轉自:C++類中成員變量的初始化總結
1. 普通的變量:
一般不考慮啥效率的情況下 可以在構造函數中進行賦值。考慮一下效率的可以再構造函數的初始化列表中進行。
1 class CA
2 {
3 public:
4 int data;
5 public:
6 CA();
7 };
8
9 CA::CA():data(0) //……#1……初始化列表方式
10 {
11 //data = 0;//……#1……賦值方式
12 };
2 {
3 public:
4 int data;
5 public:
6 CA();
7 };
8
9 CA::CA():data(0) //……#1……初始化列表方式
10 {
11 //data = 0;//……#1……賦值方式
12 };
2、static 靜態變量:
static變量屬於類所有,而不屬於類的對象,因此不管類被實例化了多少個對象,該變量都只有一個。在這種性質上理解,有點類似於全局變量的唯一性。
1 class CA
2 {
3 public:
4 static int sum;
5
6 public:
7 CA();
8 };
9 int CA::sum=0; //……#2……類外進行初始化
2 {
3 public:
4 static int sum;
5
6 public:
7 CA();
8 };
9 int CA::sum=0; //……#2……類外進行初始化
3、const 常量變量:
const常量需要在聲明的時候即初始化。因此需要在變量創建的時候進行初始化。一般采用在構造函數的初始化列表中進行。
1 class CA
2 {
3 public:
4 const int max;
5 public:
6 CA();
7 };
8
9 CA::CA():max(100)
10 {
11 }
2 {
3 public:
4 const int max;
5 public:
6 CA();
7 };
8
9 CA::CA():max(100)
10 {
11 }
4、Reference 引用型變量:
引用型變量和const變量類似。需要在創建的時候即進行初始化。也是在初始化列表中進行。但需要注意用Reference類型。
1 class CA
2 {
3 public:
4 int init;
5 int& counter;
6 public:
7 CA();
8 };
9
10 CA::CA(): counter(&init)
11 {
12 }
2 {
3 public:
4 int init;
5 int& counter;
6 public:
7 CA();
8 };
9
10 CA::CA(): counter(&init)
11 {
12 }
5、const static integral 變量:
對於既是const又是static 而且還是整形變量,C++是給予特權的(但是不同的編譯器可能有會有不同的支持,VC 6好像就不支持)。可以直接在類的定義中初始化。short可以,但float的不可以哦。
1 // 例float類型只能在類外進行初始化
2 // const float CA::fmin = 3.14;
3 class CA
4 {
5 public:
6 //static const float fmin = 0.0;// only static const integral data members can be initialized within a class
7 const static int nmin = 0;
8 ……
9 public:
10 ……
11 };
2 // const float CA::fmin = 3.14;
3 class CA
4 {
5 public:
6 //static const float fmin = 0.0;// only static const integral data members can be initialized within a class
7 const static int nmin = 0;
8 ……
9 public:
10 ……
11 };
總結起來,可以初始化的情況有如下四個地方:
1、在類的定義中進行的,只有const 且 static 且 integral 的變量。
2、在類的構造函數初始化列表中, 包括const對象和Reference對象。
3、在類的定義之外初始化的,包括static變量。因為它是屬於類的唯一變量。
4、普通的變量可以在構造函數的內部,通過賦值方式進行。當然這樣效率不高。