全局情況下: 限制標識符為內(nèi)連接,其他編譯單元不可見
局部變量時: 聲明此變量在其他編譯單元中定義
靜態(tài)成員的初始化表達式在一個類的作用域中:
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的作用域擴展至全部定義中。
如果下面再添加一個全局變量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;
}

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