1. 程式人生 > >C++11中類資料成員初始化方法詳解

C++11中類資料成員初始化方法詳解

C++98為類中提供類成員的初始化列表。

類物件的構造順序是這樣的:1.分配記憶體,呼叫建構函式時,隱式/顯示的初始化各資料成員 2.進入建構函式後在建構函式中執行一般計算
  1.類裡面的任何成員變數在定義時是不能初始化的。
  2.一般的資料成員可以在建構函式中初始化。
  3.const資料成員必須在建構函式的初始化列表中初始化。
  4.static要在類的定義外面初始化。   
  5.陣列成員是不能在初始化列表裡初始化的。
  6.不能給陣列指定明顯的初始化。  

這6條一起,說明了一個問題:C++裡面是不能定義常量陣列的!因為3和5的矛盾。這個事情似乎說不過去啊?沒有辦法,我只好轉而求助於靜態資料成員或者使用列舉。

但是在C++11中,我們可以利用類內初始化:

int j = 15;
class Bclass
{
private:
	int f = 100;
	float g = 200.0;
	const float h = 30.0;
	const int a=10;
	//  const int array[20];
	//  int thesecondarray[20] = { 0 };
	int &b=j;
	int &k = f;
	static int c;
	static const int d=30;
	static const float e;
	static const int d=30;
	static
constexpr float g=9.5f;
        static constexpr float int m[3]={0,1,2};
 public:Bclass(){//  array[20] = { 0 };       註釋去掉有錯誤//thesecondarray[20] = { 0 };}void print(){cout << a << " "<< b << "  "<< c << "  "<< d << "  "<< e << "  "<< f << "  "
<< g << "  "<< h << "  "<< k << endl;//for (int i = 0; i < 20; ++i)//cout << array[i] << "  ";//for (int i = 0; i < 20; ++i)//cout << thesecondarray[i] << "   ";}};int Bclass::c = 20;const float Bclass::e = 40.0; 可以看到基本型別不用多說,可以在類內初始化。在這裡我們重點看const 與static,引用,以及陣列。const  的int 與float都能在類內初始化。但是static還是隻有static const int 能在類內初始化,其他的static 還是能在類外初始化。而引用則可以在類內初始化。而無論是const 陣列還是非const 陣列,都不能在類內顯示初始化。其中 int m[3] 為整型陣列資料成員, 所以應該用constexpr表示式。關於constexpr和const的區別如下:

const是表明這個值是constant的,但是不必在編譯期確定,然而陣列的大小是需要在編譯期確定的,如:

int i; // not constant
const int size = i; // fine!
int arr[size]; // Error!
然而對於constexpr,則表明這個值不僅是constant的,而且也是編譯期確定的,於是,constexpr修飾的是可以用於陣列大小的。
int i; // not constant
constexpr int size = i; // Error!