c++ - 无法设置静态对象字段的值(错误 LNK2001 : unresolved external symbol)

标签 c++ static compiler-errors

我有一段看似简单明了的代码,它是我在编写的游戏中遇到的问题的简化版本。我试图将一个类中的静态字段设置为我的主方法中的另一个值。 但是这段代码不会,我不明白为什么。

我收到错误

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:

...

  1. 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/

相关文章:

c++ - 无法编译使用 ncurses 的 C/C++ 代码

c++ - MSVC编译器认为我正在引用已删除的函数,但据我所知,我不是

c++ - 提升共享指针自定义删除器示例

c++ - 使用 g++ 构建的 C++ 中的运行时数组边界检查

static - 静态类的 Powermock 给出错误 : java. lang.NoClassDefFoundError: Could not initialize class XXX

java - 为什么 java 中的 main 方法是静态的

使用 decltype(var) 后跟内部类型 "var"时出现 C++11 编译器错误

c++ - 如何运行 .h 中的函数列表

c++ - QtOpengl的演变

Java - 选择什么更好,静态方法还是非静态方法