Defining private static class member

北慕城南 提交于 2019-12-06 07:36:59

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;

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.

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

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

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.

Lightness Races with Monica

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.

Rohit

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