C++中同一个类的静态成员变量
我正在尝试创建一个包含指向其自身实例的静态指针的类。下面是一个示例:
Ah:
#include <iostream>
#ifndef _A_H
#define _A_H
class A {
static A * a;
};
A * a = NULL;
#endif
但是,当我在另一个文件中包含 Ah 时,例如:
#include "A.h"
class B {
};
我收到以下错误:
ld: duplicate symbol _a in /Users/helixed/Desktop/Example/build/Example.build/Debug/Example.build/Objects-normal/x86_64/B.o and /Users/helixed/Desktop/Example/build/Example.build/Debug/Examplebuild/Objects-normal/x86_64/A.o
我在 Mac OS X Snow Leopard 上使用 Xcode 默认编译器。
I'm trying to create a class which contains a static pointer to an instance of itself. Here's an example:
A.h:
#include <iostream>
#ifndef _A_H
#define _A_H
class A {
static A * a;
};
A * a = NULL;
#endif
However, when I include A.h in another file, such as:
#include "A.h"
class B {
};
I get the following error:
ld: duplicate symbol _a in /Users/helixed/Desktop/Example/build/Example.build/Debug/Example.build/Objects-normal/x86_64/B.o and /Users/helixed/Desktop/Example/build/Example.build/Debug/Examplebuild/Objects-normal/x86_64/A.o
I'm using the Xcode default compiler on Mac OS X Snow Leopard.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
因为全局变量
a
是在A.cpp
和B.cpp
中定义的。一个公共符号只需在一处定义。其余的可以通过链接知道该符号的内容是什么。将
A* a = NULL
行从Ah
移至A.cpp
。(顺便说一句,要引用类
A
中的a
,请使用A* A::a = NULL;
,否则您将创建全局命名空间中的a
。)Because the global variable
a
is defined in bothA.cpp
andB.cpp
. One public symbol only needs to be defined in one place. The rest can know what the content of that symbol by linking.Move the
A* a = NULL
line away fromA.h
toA.cpp
.(BTW, to refer to the
a
in the classA
, useA* A::a = NULL;
, otherwise you're creating ana
in the global namespace.)此行:
需要如下所示:
并且您需要将其从头文件中移出,并将其放入源(.cpp)文件中。
静态成员的定义在程序中只能存在一次。如果将此行放入头文件中,它将包含在包含它的每个源文件中,从而导致重复符号错误。
This line:
needs to look like this:
And you need to move it out of the header file, and put it in a source (.cpp) file.
The definition of a static member must exist only once in your program. If you put this line in the header file, it would be included in every source file which includes it, leading to a duplicate symbol error.