Looks like I can init a POD static const member, but not other types:
struct C {
static const int a = 42; // OK
static const string b = "hi"; // compile error
};
Why?
The syntax initializer in the class definition
is only allowed with integral and enum types. For std::string
, it must be defined outside the class definition and initialized there.
struct C {
static const int a = 42;
static const string b;
};
const string C::b = "hi"; // in one of the .cpp files
static members
must be defined in one translation unit to fulfil the one definition rule. If C++ allows the definition below;
struct C {
static const string b = "hi";
};
b
would be defined in each translation unit that includes the header file.
C++ only allows to define const static
data members of integral
or enumeration
type in the class declaration as a short-cut. The reason why const static
data members of other types cannot be defined is that non-trivial initialization would be required (constructor needs to be called).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With