How to initialize static members in the header

前端 未结 8 1148
伪装坚强ぢ
伪装坚强ぢ 2020-12-13 09:02

Given is a class with a static member.

class BaseClass
{
public:
    static std::string bstring;
};

String has obviously to be default-

8条回答
  •  青春惊慌失措
    2020-12-13 09:06

    UPDATE: My answer below explains why this cannot be done in the way suggested by the question. There are at least two answers circumventing this; they may or may not solve the problem.


    The bstring static member has to be linked to a specific memory address. For this to happen, it has to appear in a single object file, therefore it has to appear in a single cpp file. Unless you're playing with #ifdef's to make sure this happens, what you want cannot be done in the header file, as your header file may be included by more than one cpp files.

提交回复
热议问题