开发者

Why must the static member be initialized outside main()?

开发者_Python百科

Why is this invalid in C++?

class CLS
{
public:
    static int X;
};

int _tmain(int argc, _TCHAR* argv[])
{
    CLS::X=100;
    return 0;
}


They can be changed inside of main, like in your example, but you have to explicitely allocate storage for them in global scope, like here:

class CLS
{
public:
        static int X;
};

int CLS::X = 100; // alocating storage, usually done in CLS.cpp file.


int main(int argc, char* argv[])
{
        CLS::X=100;
        return 0;
}


It isn't that the static member must be INITIALIZED at global scope, but rather that the static member must have storage allocated for it.

class CLS {
public:
  static int X;
};

int CLS::X;

int _tmain(int argc, _TCHAR* argv[])
{
  CLS::X=100;
  return 0;
}


Once you define a static data member, it exists even though no objects of the static data member's class exist. In your example, no objects of class X exist even though the static data member CLS::X has been defined.


static members aren't part of class object but they still are part of class scope. they must be initialized independently outside of class same as you would define a member function using the class scope resolution operator.

int CLS::X=100;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜