我在课堂上有一个静态变量.我正在全球范围内初始化它,效果很好.
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内部初始化静态类变量
发布评论