Static Data Member Initialization

2019-01-04 01:45发布

Why must static data member initialization be outside the class?

class X
{
public:
      int normalValue = 5; //NSDMI
      static int i;
};

int X::i = 0;

Why is the static data member (here "i") only a declaration, not a definition?

标签: c++ c++11 g++
7条回答
来,给爷笑一个
2楼-- · 2019-01-04 02:32

You need to supply a separate definition for a static data member (if its odr-used, as defined in C++11) simply because that definition shall reside somewhere - in one and only one translation unit. Static class data members are basically global objects (global variables) declared in class scope. The compiler wants you to choose a specific translation unit that will hold the actual "body" of each global object. It is you who has to decide which translation unit to place the actual object to.

查看更多
登录 后发表回答