在main内部初始化静态类变量 [英] Initialization of static class variable inside the main

查看:42
本文介绍了在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;

因为在我的课堂上,我将iCount定义为整数类型,为什么不呢?

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

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

推荐答案

C ++标准的$ 9.4.2/7部分说,

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

静态数据成员已初始化完全像非本地一样销毁了对象(3.6.2、3.6.3).

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.

实际上,静态成员更像是通过 Myclass :: iCount 访问的全局对象.因此,您必须在全局范围(定义类的相同范围)上初始化它们,如下所示:

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 ****/
}

相似的主题:

静态成员变量如何影响对象大小?

这篇关于在main内部初始化静态类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆