what开发者_运维问答's wrong with the following code:
class A
{
public:
static A* p;
A()
{
p = this;
}
};
I got this link error:
error LNK2001: unresolved external symbol "public: static class A * A::p" (?p@A@@2PAV1@A)
I cannot figure out the point of this problem, please help..
You need storage for that pointer. You declared, but did not define it. In the implementation (.cpp
) file do:
A* A::p;
Edit 0:
By the way, do you really want to override that pointer every time a new instance of your class in created? Seems to me you are looking for the Singleton pattern.
Edit 1:
You can initialize static variables (and not unlike in Java, come to think of it, though the syntax is different). Say you have a static string member foo
of a class X
, then your implementation file might contain the following:
std::string X::foo = "Happy Leif Erikson Day!";
But be careful - constructors for static objects run before main()
is entered and their order between translation units is undefined, which often leads to "static initialization order fiasco".
精彩评论