可能重复:
static members and LNK error in C++
What does it mean to have an undefined reference to a static member?
我有这堂课:
class A_GItem
{
public:
void create_item();
private:
static int static_index;
}
create_item函数简单如下:
void create_item() { static_index++; }
编译时(干净后,尝试解决问题)我有: 错误LNK2001:未解析的外部符号“private:static int A_GItem :: static_index
有什么想法吗?感谢
答案 0 :(得分:3)
成员静态变量需要初始化。您只是在标题中声明了您的变量,但没有定义它:
//A_GItem.h
class A_GItem
{
public:
void create_item();
private:
static int static_index;
}
//A_GItem.cpp
int A_GItem::static_index = 0;
答案 1 :(得分:2)
您必须实际定义静态成员变量
int A_GItem::static_index;
在一个.cpp文件中。