全局情況下: 限制標(biāo)識(shí)符為內(nèi)連接,其他編譯單元不可見(jiàn)
局部變量時(shí): 聲明此變量在其他編譯單元中定義
靜態(tài)成員的初始化表達(dá)式在一個(gè)類的作用域中:
int x = 100;

class WithStatic


{
static int x;
static int y;
};

int WithStatic:: x = 1;
int WithStatic:: y = x +1;

int main()


{
WithStatic ws;
return 0;
}上例中,WithStatic:: x = 1; WithStatic:: y = 2;原因是:WithStatic::限定符把WithStatic的作用域擴(kuò)展至全部定義中。
如果下面再添加一個(gè)全局變量int y = x + 1;那么y = 101;
另外,靜態(tài)數(shù)據(jù)變量的初始化(定義)是在類外的,而且只定義一次。
但是static const又稍稍有些不同
1. 內(nèi)建數(shù)據(jù)類型可以在類內(nèi)定義,也可以在類外定義。
2. 內(nèi)建數(shù)據(jù)類型數(shù)組必須在類外定義。
3. 自定義類型并須在類外定義。
例:
class Test


{
static int i = 1;// illegal! only static const integral data members can be initialized within a class

static const int y = 1;// right
static const int z[];

static const int q[] =
{1, 2, 4};//illegal
};


const int Test::z[] =
{ 1, 2, 3};內(nèi)建類型同樣要在類外定義:
class X


{
int i;
public:
X(int ii):i(ii)

{}
};

class test


{
//This doesn't work, although you want it to:
static const X x(100);// illegal, both const and non-const static class objects must be initialized externally:
static X x2;
static X xTable2[];
static const X x3;
static X xTable3[];
};
X test::x2(100);

X test::xTable2[]=
{
X(1), X(2)};

const X test::x3(100);

const X test::xTable3[]=
{
X(1), X(2)};
int main()


{//
return 0;
}

究其原因,我覺(jué)得是因?yàn)檫@個(gè)靜態(tài)變量屬于類,而不屬于對(duì)象,所以,不能在創(chuàng)建這個(gè)對(duì)象的時(shí)候初始化它,那樣就會(huì)在棧中為這個(gè)變量分配內(nèi)存,而不能成為靜態(tài)變量。所以必須不是在創(chuàng)建對(duì)象的時(shí)候初始化,而應(yīng)該是在連接器知道這個(gè)類的時(shí)候,這個(gè)靜態(tài)成員就應(yīng)該創(chuàng)建好了。為什么不是編譯器而是連接器呢,我也不知道了。。。編譯原理沒(méi)看過(guò),先用著。
補(bǔ)充:
靜態(tài)數(shù)據(jù)成員可以放在嵌套類中,但是不能放在局部類中,我認(rèn)為原因是每次調(diào)用該函數(shù)時(shí),都需要壓棧操作,然而一個(gè)類中的靜態(tài)變量也要放在棧上,這樣就不被允許了。
2. 靜態(tài)成員函數(shù)不能為const(為什么?)
細(xì)看const成員函數(shù)的定義:不會(huì)修改該對(duì)象的數(shù)據(jù)成員。
我們知道,訪問(wèn)成員函數(shù)時(shí)會(huì)自動(dòng)帶上this,形如CTest::SetColor(int color),會(huì)自動(dòng)轉(zhuǎn)換成CTest::SetColor(CTest* this, int color)。
在const成員函數(shù)時(shí),實(shí)際轉(zhuǎn)換成了CTest::SetColor(const CTest* this, int color)。
this指向的是一個(gè)const對(duì)象,const對(duì)象的數(shù)據(jù)成員是不能改變的。
而靜態(tài)成員函數(shù)實(shí)際上是一個(gè)全局函數(shù),沒(méi)有this指針,根本不會(huì)訪問(wèn)到對(duì)象的數(shù)據(jù)成員,在此使用const就多此一舉了。
posted on 2012-04-09 14:09
Dino-Tech 閱讀(206)
評(píng)論(0) 編輯 收藏 引用