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

Pau*_*cks 27 c++ static class

重复:
C++:对静态类成员的未定义引用

如果我有这样的类/结构

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

// implementation
int Foo::adder()
{
   return baz + bar;
}
Run Code Online (Sandbox Code Playgroud)

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

Dra*_*sha 60

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

int Foo::bar = you_initial_value_here;
Run Code Online (Sandbox Code Playgroud)

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


Chr*_*ung 16

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

int Foo::bar = 0;  // or whatever value you want
Run Code Online (Sandbox Code Playgroud)


Art*_*yom 15

你需要添加一行:

int Foo::bar;
Run Code Online (Sandbox Code Playgroud)

这将定义您的存储.类中静态的定义类似于"extern" - 它提供符号但不创建它.即

foo.h中

class Foo {
    static int bar;
    int adder();
};
Run Code Online (Sandbox Code Playgroud)

Foo.cpp中

int Foo::bar=0;
int Foo::adder() { ... }
Run Code Online (Sandbox Code Playgroud)