//foo.h
class Foo
{
private:
static int number;
public:
static int bar();
};
//foo.cc
#include "foo.h"
int Foo::bar()
{
return Foo::number;
}
这不起作用。我想在类定义之外定义静态函数并访问静态值。
undefined reference to `Foo::number'
答案 0 :(得分:7)
您刚刚声明了您需要定义的静态成员。 在cpp文件中添加它。
int Foo::number = 0;
这应该是一个很好的阅读:
<强> what is the difference between a definition and a declaration? 强>
答案 1 :(得分:2)
您必须定义Foo::number
:
// foo.cc
...
int Foo::number(0);
答案 2 :(得分:1)
您已声明Foo :: number,您必须添加定义。在你的cpp文件中添加这一行
int Foo::number = 0;