在C ++中定义静态成员 [英] Defining static members in C++

查看:152
本文介绍了在C ++中定义静态成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图定义一个公共静态变量,如下所示:

  public:
static int j = 0 ; //或任何其他值太多

我在这行上得到一个编译错误:ISO C ++ forbids


  1. 为什么在C ++中不允许这样做?


  2. 这意味着C ++中的静态变量


谢谢!

解决方案


(1。)为什么不允许在C ++中?



$ b b

Bjarne Stroustrup的C ++风格和技巧常见问题类通常在头文件中声明,并且头文件通常包括在许多翻译单元中。然而,为了避免复杂的链接器规则,C ++要求每个对象都有唯一的定义。如果C ++允许需要在内存中作为对象存储的实体的类定义,那么该规则将被破坏。


(2。)为什么允许const成员
初始化?


[ dirkgently更好]


(3。)在C ++中,这意味着静态变量
不会在C中初始化为0


知道,只要你在.cpp中声明了静态成员var,如果没有指定,它将被初始化为零:

  // in some .cpp 
int Test :: j; // j = int();


I am trying to define a public static variable like this :

public :
         static int j=0;        //or any other value too

I am getting a compilation error on this very line : ISO C++ forbids in-class initialization of non-const static member `j'.

  1. Why is it not allowed in C++ ?

  2. Why are const members allowed to be initialized ?

  3. Does this mean static variables in C++ are not initialized with 0 as in C?

Thanks !

解决方案

(1.) Why is it not allowed in C++ ?

From Bjarne Stroustrup's C++ Style and Technique FAQ: A class is typically declared in a header file and a header file is typically included into many translation units. However, to avoid complicated linker rules, C++ requires that every object has a unique definition. That rule would be broken if C++ allowed in-class definition of entities that needed to be stored in memory as objects.

(2.) Why are const members allowed to be initialized ?

[dirkgently said it better]

(3.) Does this mean static variables in C++ are not initialized with 0 as in C?

As far as I know, as long as you declare the static member var in a .cpp it will be zero-initialized if you don't specify otherwise:

// in some .cpp
int Test::j; // j = int();

这篇关于在C ++中定义静态成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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