Defining private static class member

两盒软妹~` 提交于 2019-12-08 01:49:05

问题


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;


来源:https://stackoverflow.com/questions/4579794/defining-private-static-class-member

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!