开发者

Static Member Variables of the Same Class in C++

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"开发者_JS百科

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.


This line:

A * a = NULL;

needs to look like this:

A *A::a = NULL;

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.


Because the global variable a is defined in both A.cpp and B.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 from A.h to A.cpp.

(BTW, to refer to the a in the class A, use A* A::a = NULL;, otherwise you're creating an a in the global namespace.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜