Defining private static class member

2019-05-28 22:16发布

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?

6条回答
爷、活的狠高调
2楼-- · 2019-05-28 23:00

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楼-- · 2019-05-28 23:01

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.

查看更多
Melony?
4楼-- · 2019-05-28 23:01

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;
查看更多
姐就是有狂的资本
5楼-- · 2019-05-28 23:03

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.

查看更多
闹够了就滚
6楼-- · 2019-05-28 23:11

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;
查看更多
贪生不怕死
7楼-- · 2019-05-28 23:19

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

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

查看更多
登录 后发表回答