定义私有静态类成员
class B { /* ... */ };
class A {
public:
A() { obj = NULL; }
private:
static B* obj;
};
然而,这会产生大量链接器错误,符号 obj 无法解析。
拥有此类私有静态类成员而没有这些链接器错误的“正确”方法是什么?
class B { /* ... */ };
class A {
public:
A() { obj = NULL; }
private:
static B* obj;
};
However this produces huge mass of linker errors that symbol obj is unresolved.
What's the "correct" way to have such private static class member without these linker errors?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您需要这样定义:
这是在标题中:
这是在源代码中
You need to define like this :
this is in the header :
this is in the source
您需要添加
到您的 cpp 文件之一。另请注意,如果您在 A 的构造函数中设置 obj,这意味着每当您创建 A 对象时,您都会再次重置 obj - 因为它是静态的,所以只有一个 obj 在所有 A 实例之间共享。
You need to add
to one of your cpp files. Also note that if you set obj in A's constructor, that means that whenever you create an A object you reset obj again - since it is static, there is only one obj that is shared among all A instances.
http://www.parashift.com/c++-faq/ctors.html #faq-10.12
(正如 @peoro 指出的,请记住以
;
结束每个类定义)。http://www.parashift.com/c++-faq/ctors.html#faq-10.12
(And as @peoro noted, please remember to end every class definition with a
;
).您必须在 cpp 文件中初始化 obj:
不允许在构造函数中初始化它,因为它是静态变量。
You have to initialize obj in a cpp file:
You are not allowed to initialize it in a constructor, since it is a static variable.
您声明了静态成员,但没有定义它。
此外,每当构造 A 的任何实例时,您都可以设置它的值,而实际上您只希望它初始化一次。
由于您的 A 类定义可能位于头文件中,因此您应该确保 obj (我添加的)的定义位于一个(且仅一个).cpp 文件中。这是因为它在你编译的项目中只能出现一次,但头文件的内容可能会出现多次
#included
。You declared the static member, but you did not define it.
Further, you set its value whenever any instance of A is constructed, whereas in fact you only want it initialised once.
As your class A definition is probably in a header file, you should ensure that the definition of obj (that I added) goes in one (and one only) .cpp file. This is because it must appear only once in your compiled project, but the contents of the header file may be
#included
multiple times.链接错误是因为您还需要在类定义之外声明静态变量纯粹是为了链接目的和静态内存分配:
Linking errors are because you also need to declare static variables outside class definition purely for linking purpose and static memory allocation as