Initialization of static class variable inside the main

核能气质少年 提交于 2021-02-04 13:36:08

问题


I have a static variable in the class. I am Initializing that in the global scope, its works fine.

But When I try to Initialize in the main linker throws an error. Why it so.

class Myclass{

    static int iCount;
} ;

int main(){

  int Myclass::iCount=1;

}

And In global scope why I have to specify the variable type like

int Myclass::iCount=1;

As In my class I am definig iCount as integer type why not.

   Myclass::iCount =1 ; in //Global scope

回答1:


The section $9.4.2/7 from the C++ Standard says,

Static data members are initialized and destroyed exactly like non-local objects (3.6.2, 3.6.3).

Note the phrases "initialized" and "exactly like non-local objects". Hope that explains why you cannot do that.

In fact, static members are more like global objects accessed through Myclass::iCount. So, you've to initialize them at global scope (the same scope at which class is defined), like this:

class Myclass{

    static int iCount;
} ;
int Myclass::iCount=1;

int main(){
  /*** use Myclass::iCount here ****/
}

Similar topic:

How do static member variables affect object size?




回答2:


Because C++ syntax doesn't allow this. You need to instantiate your static variable outside of the scope of some function.

Besides you forget a semicolon ; after your class ending bracket.




回答3:


this is the correct C++. Outside of a function, in a cpp file. the initialisation is done at the beginning/launching of the executable. ( even before calling main() );

//main.h

class Myclass{

    static int iCount;
}; // and don't forget this ";" after a class declaration


//main.cpp

int Myclass::iCount=1;

int main(){



}



回答4:


From C++ standard (§8.5/10):

An initializer for a static member is in the scope of the member’s class.

class Myclass has global scope and you tried to initialize its static member in the narrower scope - of the function main.




回答5:


The static initialisation occurs before main is called by the run-time initialisation.

Placing it within a function is not allowed because that is where locally scoped objects are declared. It would be confusing and ambiguous to allow that.



来源:https://stackoverflow.com/questions/4699084/initialization-of-static-class-variable-inside-the-main

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!