从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.
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();
}
5 回答
从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.
[dirkgently said it better]
据我所知,只要你在.cpp中声明静态成员var,如果你没有另外指定,它将被零初始化:
您必须在.cpp文件中初始化静态变量,而不是在类声明中 .
在类中声明静态变量时,可以在不实例化类的情况下使用它 .
除非您定义它,否则变量不会成为l值 .
即使在这种情况下,如果要获取变量的地址,也需要定义 .
此外,这主要是一个使用工件,所以你可以写:
不,是他们:
虽然事情在C 0x中变得更加棘手 . 现在可以初始化所有文字类型(而不是当前标准中的整数类型),这意味着现在可以使用声明中的初始化程序初始化所有标量类型(包括浮点数)和某些类类型 .
简短的回答:
这相当于说
extern int Test_j = 0;
.如果确实编译了,会发生什么?包含类的头文件的每个源文件都会定义一个名为Test :: j的符号,该符号初始化为0.链接器往往不喜欢这样 .