无法设置静态对象字段的值(错误LNK2001:未解析的外部符号) [英] Can't set value of static object field (error LNK2001: unresolved external symbol)
问题描述
我有一个看似简单和直接的代码段,这是我在写的游戏中遇到的一个问题的简化版本。我试图在一个类中的静态字段设置为另一个值从我的主要方法。
然而这个代码不会,我不明白为什么。
我收到错误
1> Source.obj:error LNK2001:未解析的外部符号public:
static class A * B :: a(?a @ B @@ 2PAVA @@ A)
$ b b
class A
{
public:
A()
{
} $ b b};
class B
{
public:
static A * a;
};
int main()
{
B :: a = new A;
}
什么规则说我必须定义我的静态类成员
但是定义的规则是什么?
定义和ODR
定义是完全定义由声明引入的实体的声明。每个声明都是一个定义,除了以下:
...
4)在类定义内声明静态数据成员
< blockquote>
struct S {//定义S
int n; // define S :: n
static int i; // declares,but does not define S :: i
};
int S :: i = 0; //定义和初始化S :: i
作为一个额外的参考,你也可以在这里检查维基百科,一种定义规则
UPDATE:
我终于找到了目前的(2014年6月2日)最新免费提供的标准参考资料(目前发布的标准的副本可用于约30美元我认为):
§9.4.2
2 静态数据成员在其类定义中的声明不是定义,可能是不完全的
的范围内
类型,而不是cv-qualied void。静态数据成员的定义应出现在包含成员类类定义的命名空间
范围中。在命名空间范围的定义中,静态
数据成员的名称应该使用::运算符通过其类名来定义。静态数据成员的
定义中的初始化表达式在其类
I have seemingly simple and straightforward segment of code that is a simplified version of a problem I have been having in a game I am writing. I am trying to set a static field in one class to another value from my main method. However this code will not and I don't understand why.
I get the error
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; }
What is the rule saying that I have to define my static class member outside the class to get it linked?
解决方案As from your comment
but what is the rule that defines that?
From the c++ reference it says
Definitions and ODR
Definitions are declarations that fully define the entity introduced by the declaration. Every declaration is a definition, except for the following:
...
4) 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
As an additional reference you can also check here Wikipedia, One Definition Rule
UPDATE:
I finally found the current (2nd June 2014) latest freely available standard reference (a copy of the currently released standard is available for about 30$ I think):§ 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
这篇关于无法设置静态对象字段的值(错误LNK2001:未解析的外部符号)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!