在C ++中访问静态类变量?

时间:2009-04-13 06:43:59

标签: c++ class static

重复:
C++: undefined reference to static class member

如果我有这样的类/结构

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

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

这不起作用。我得到一个“未定义的引用`Foo :: bar'”错误。如何在C ++中访问静态类变量?

4 个答案:

答案 0 :(得分:58)

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

int Foo::bar = you_initial_value_here;

这是必需的,因此编译器可以放置静态变量。

答案 1 :(得分:16)

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

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

答案 2 :(得分:15)

您需要添加一行:

int Foo::bar;

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

foo.h中

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

Foo.cpp中

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

答案 3 :(得分:1)

在类中使用静态变量,首先你必须为静态变量(初始化)提供一个通常(没有localy)的值,然后你可以访问类中的静态成员:

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

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