我有一段看似简单明了的代码,它是我在编写的游戏中遇到的问题的简化版本。我试图将一个类中的静态字段设置为我的主方法中的另一个值。 但是这段代码不会,我不明白为什么。
我收到错误
1>Source.obj : error LNK2001: unresolved external symbol "public: static class A * B::a" (?a@B@@2PAVA@@A)
class A
{
public:
A()
{
}
};
class B
{
public:
static A* a;
};
int main()
{
B::a = new A;
}
规则是什么规定我必须在类外部定义静态类成员才能链接它?
最佳答案
根据您的评论
but what is the rule that defines that?
来自c++ reference它说
Definitions and ODR
Definitions are declarations that fully define the entity introduced by the declaration. Every declaration is a definition, except for the following:
...
- Declaration of a static data member inside a class definition
struct S { // defines S
int n; // defines S::n
static int i; // declares, but doesn't define S::i
};
int S::i = 0; // defines and initializes S::i
作为附加引用,您还可以在此处查看 Wikipedia, One Definition Rule
我终于找到了当前的(2014年6月2日)latest freely available standard reference (我认为当前发布的标准的拷贝售价约为 30 美元):
§ 9.4.2
2 The declaration of a static data member in its class definition is not a definition and may be of an incomplete type other than cv-qualified void. The definition for a static data member shall appear in a namespace scope enclosing the member’s class definition. In the definition at namespace scope, the name of the static data member shall be qualified by its class name using the :: operator. The initializer expression in the definition of a static data member is in the scope of its class
关于c++ - 无法设置静态对象字段的值(错误 LNK2001 : unresolved external symbol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23983916/