c++ - Why can one initialize non-const and static const member variables but not static member variables? -
c++ - Why can one initialize non-const and static const member variables but not static member variables? -
struct { int = 5; //ok const int b = 5; //ok static const int c = 5; //ok static int d = 5; //error! } error: iso c++ forbids in-class initialization of non-const static fellow member 'a::d'
why so? can explain me reasoning behind this?
it has info stored. here's breakdown:
int: fellow member variable, stored wherever class instance stored const int: same int static const int: doesn't need stored, can "inlined" used static int: must have single storage location in program...where?since static int mutable, must stored in actual location somewhere, 1 part of programme can modify , part can see modification. can't stored in class instance, must more global variable. why not create global variable? well, class declarations in header files, , header file may #included in multiple translation units (.cpp files). header file says "there int...somewhere." storage needs set corresponding .cpp file (like global variable).
in end, not initialization, rather storage. leave off initializer , you'd still not have valid programme until add together .cpp file:
int a::d; // initialize if want to, default 0
without this, references static int undefined , linking fail.
c++
Comments
Post a Comment