gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 01:04:25 25 4
gpt4 key购买 nike

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

我得到了错误

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 incompletetype other than cv-qualified void. The definition for a static data member shall appear in a namespacescope enclosing the member’s class definition. In the definition at namespace scope, the name of the staticdata member shall be qualified by its class name using the :: operator. The initializer expression in thedefinition of a static data member is in the scope of its class

关于c++ - 无法设置静态对象字段的值(错误 LNK2001 : unresolved external symbol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23983916/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com