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