冒號初始化列表的一個作用
?? 我們在創建C++類的時候,如果類中有const類型的變量,那么這個值的初始化就是一個問題,可以看下面一段代碼:
#include?
<
iostream
>
using ? namespace ?std;
class ?Test
{
public :
????Test( int ?i)
????{
????????identifier? = 1 ;//這里錯誤
????????cout << " Hello? " << identifier << " \n " ;
????}?
???? ~ Test()
????{
????????cout << " Googbye? " << identifier << endl;
????}
private :
???? const ? int ?identifier;
};
int ?main()
{
????Test?theWorld( 1 );
???? return ? 0 ;
}
在VC6.0下編譯的時候,無法通過,編譯器提示如下using ? namespace ?std;
class ?Test
{
public :
????Test( int ?i)
????{
????????identifier? = 1 ;//這里錯誤
????????cout << " Hello? " << identifier << " \n " ;
????}?
???? ~ Test()
????{
????????cout << " Googbye? " << identifier << endl;
????}
private :
???? const ? int ?identifier;
};
int ?main()
{
????Test?theWorld( 1 );
???? return ? 0 ;
}
error?C2758:?'identifier'?:?must?be?initialized?in?constructor?base/member?initializer?list
see?declaration?of?'identifier'
error?C2166:?l-value?specifies?const?object
see?declaration?of?'identifier'
error?C2166:?l-value?specifies?const?object
???可以看見在普通構造函數方式下是不能初始化const類型的,它是個左值。
???那么我們怎么解決這個問題呢?這里就是我要講的,使用冒號初始化列表方式。
? 再看下面的代碼:
#include?<iostream>
using?namespace?std;
class?Test
{
public:
????Test(int?i):identifier(i)//冒號初始化列表
????{
????????cout<<"Hello?"<<identifier<<"\n";
????}?
????~Test()
????{
????????cout<<"Googbye?"<<identifier<<endl;
????}
private:
????const?int?identifier;
};
int?main()
{
????Test?theWorld(1);
????return?0;
}
???? 上面這個代碼使用了冒號程序化列表,程序可以編譯通過,這樣我們就可以在對象創建的時候再給const類型的類變量賦值了。using?namespace?std;
class?Test
{
public:
????Test(int?i):identifier(i)//冒號初始化列表
????{
????????cout<<"Hello?"<<identifier<<"\n";
????}?
????~Test()
????{
????????cout<<"Googbye?"<<identifier<<endl;
????}
private:
????const?int?identifier;
};
int?main()
{
????Test?theWorld(1);
????return?0;
}
??? 輸出結果是:
Hello?1
Goodbye?1
Goodbye?1
此文完。