在main内部初始化静态类变量

编程入门 行业动态 更新时间:2024-10-26 20:34:28
本文介绍了在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内部初始化静态类变量

本文发布于:2023-11-06 07:45:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1563106.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:初始化   变量   静态   main

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!