Defining private static class member

2019-05-28 22:18发布

问题:

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?

回答1:

You need to define like this :

this is in the header :

class B { ... }

class A {
public:
    A() { obj = NULL; }
private:
    static B* obj;
}

this is in the source

B* A::obj = NULL;


回答2:

You need to add

B *A::obj = NULL;

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.



回答3:

http://www.parashift.com/c++-faq/ctors.html#faq-10.12

(And as @peoro noted, please remember to end every class definition with a ;).



回答4:

You have to initialize obj in a cpp file:

B* A::obj = NULL;

You are not allowed to initialize it in a constructor, since it is a static variable.



回答5:

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.

class B;

class A {
private:
    static B* obj;
};

B* A::obj = NULL;

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.



回答6:

Linking errors are because you also need to declare static variables outside class definition purely for linking purpose and static memory allocation as

B* A::obj;