简体   繁体   English

在main中初始化静态类变量

[英]Initialization of static class variable inside the main

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. 在我的课堂上,我将iCount定义为整数类型,为什么不呢。

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

The section $9.4.2/7 from the C++ Standard says, C ++标准中的$ 9.4.2 / 7部分说,

Static data members are initialized and destroyed exactly like non-local objects (3.6.2, 3.6.3). 静态数据成员的初始化和销毁与非本地对象完全相同 (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 . 实际上,静态成员更像是通过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? 静态成员变量如何影响对象大小?

Because C++ syntax doesn't allow this. 因为C ++语法不允许这样做。 You need to instantiate your static variable outside of the scope of some function. 您需要在某个函数范围之外实例化静态变量。

Besides you forget a semicolon ; 除此之外你忘了分号; after your class ending bracket. 在你的班级结束括号之后。

this is the correct C++. 这是正确的C ++。 Outside of a function, in a cpp file. 在函数外部,在cpp文件中。 the initialisation is done at the beginning/launching of the executable. 初始化在可执行文件的开始/启动时完成。 ( even before calling main() ); (甚至在调用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(){



}

From C++ standard (§8.5/10): 从C ++标准(§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 . class Myclass具有全局范围,并且您尝试在函数main的较窄范围内初始化其静态成员。

The static initialisation occurs before main is called by the run-time initialisation. 静态初始化发生运行时初始化调用main 之前

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. 允许这样做会让人感到困惑和含糊。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM