2009-04-13 249 views

回答

53

您必须添加在实施文件中的以下行:

int Foo::bar = you_initial_value_here; 

这是必需的,因此编译器提供了静态变量的地方。

16

这是正确的语法,但Foo::bar必须单独定义,在头之外。在您的.cpp文件中的一个,这样说:

int Foo::bar = 0; // or whatever value you want 
+0

Hello Chris,如果我们在C++中有这么多的公共静态类成员变量(非多线程源代码),是否有什么错误?我已经将一些全局变量作为公共静态移动到一个类中。 – sree 2015-05-26 15:02:55

15

您需要添加一行:

int Foo::bar; 

这将定义你的存储。类中静态的定义类似于“extern” - 它提供了符号,但不创建符号。即

foo.h中

class Foo { 
    static int bar; 
    int adder(); 
}; 

Foo.cpp中

int Foo::bar=0; 
int Foo::adder() { ... } 
1

用于类的静态变量,在首先你必须向你的静态变量generaly(无localy)给出一个值(初始化),那么你可以在类中访问一个静态成员:

class Foo 
{ 
    public: 
    static int bar; 
    int baz; 
    int adder(); 
}; 

int Foo::bar = 0; 
// implementation 
int Foo::adder() 
{ 
    return baz + bar; 
}