首页 文章

在C中定义静态成员

提问于
浏览
25

我试图定义一个这样的公共静态变量:

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

我在这一行得到了一个编译错误:ISO C禁止非const静态成员`j'的类内初始化 .

  • 为什么在C中不允许?

  • 为什么允许const成员初始化?

  • 这是否意味着C中的静态变量未在C中初始化为0?

谢谢 !

5 回答

  • 17

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

    Bjarne Stroustrup's C++ Style and Technique FAQA 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.)为什么允许const成员初始化?

    [dirkgently said it better]

    (3.)这是否意味着C中的静态变量未在C中初始化为0?

    据我所知,只要你在.cpp中声明静态成员var,如果你没有另外指定,它将被零初始化:

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

    您必须在.cpp文件中初始化静态变量,而不是在类声明中 .

    在类中声明静态变量时,可以在不实例化类的情况下使用它 .

    //Header file
    class Test
    {
      public:
        static int j;
    };
    
    //In cpp file
    
    //Initialize static variables here.
    int Test::j = 0;
    
    //Constructor
    Test::Test(void)
    {
       //Class initialize code
    }
    
  • 8

    为什么C不允许?

    除非您定义它,否则变量不会成为l值 .

    为什么允许const成员初始化?

    即使在这种情况下,如果要获取变量的地址,也需要定义 .

    9.4.2静态数据成员2在类定义中声明静态数据成员不是定义,除了cv-qualified void之外,可能是不完整的类型 . 静态数据成员的定义应出现在包含成员类定义的命名空间范围内 . 在命名空间作用域的定义中,静态数据成员的名称应使用::运算符通过其类名限定 . 静态数据成员定义中的初始化表达式在其类的范围内

    此外,这主要是一个使用工件,所以你可以写:

    class S {
          static const int size = 42;
          float array[ size ];
    };
    

    这是否意味着C中的静态变量未在C中初始化为0?

    不,是他们:

    3.6.2非局部变量的初始化在进行任何其他初始化之前,具有静态存储持续时间(3.7.1)或线程存储持续时间(3.7.2)的变量应为零初始化(8.5) .

    虽然事情在C 0x中变得更加棘手 . 现在可以初始化所有文字类型(而不是当前标准中的整数类型),这意味着现在可以使用声明中的初始化程序初始化所有标量类型(包括浮点数)和某些类类型 .

  • 2

    简短的回答:

    这相当于说 extern int Test_j = 0; .

    如果确实编译了,会发生什么?包含类的头文件的每个源文件都会定义一个名为Test :: j的符号,该符号初始化为0.链接器往往不喜欢这样 .

  • 18
    class GetData        
    {    
    private:     
    static int integer;   //Static variable must be defined with the extension of keyword static;      
    public:      
    static void enter(int x)      
    {       
    integer = x;  //static variable passed through the static function    
    }
    static int  show()   //declared and defined
    {
        return integer;   //will return the integer's value
    }        
    };        
    int GetData::integer = 0;    //Definition of the static variable       
    int main()      
    {      
       GetData::enter(234);    //value has been passed through the static function enter. Note that class containing static variables may not have the object in main. They can be called by scope resolution operator in main.
       cout<<GetData::show();      
    }
    

相关问题