How to initialize static members in the header

2019-02-02 03:06发布

Given is a class with a static member.

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

String has obviously to be default-initialized outside of the class.

std::string BaseClass::bstring {"."};

If I include the above line in the header along with the class, I get a symbol multiply defined error. It has to be defined in a separate cpp file, even with include guards or pragma once.

Isn't there a way to define it in the header?

7条回答
狗以群分
2楼-- · 2019-02-02 03:41

Regarding

Isn't there a way to define [the static data member] in the header?

Yes there is.

template< class Dummy >
struct BaseClass_statics
{
    static std::string bstring;
};

template< class Dummy >
std::string BaseClass_statics<Dummy>::bstring = ".";

class BaseClass
    : public BaseClass_statics<void>
{};

An alternative is to use a function, as Dietmar suggested. Essentially that is a Meyers' singleton (google it).

Edit: Also, since this answer was posted we've got the inline object proposal, which I think is accepted for C++17.

Anyway, think twice about the design here. Globals variables are Evil™. This is essentially a global.

查看更多
登录 后发表回答