Look at the code below, this const static int num1 = 8; compiles. However, the const static double num2 = 8.8; code gives an error. Their modifiers are all const static, so why does int work, but double and other floating-point types result in an error?
struct S {
const static int num1 = 8; // OK
const static double num2 = 8.8; // error
};
I've tried some built-in types of C++ and found that
- integer members such as
int,short,long, andcharcan be defined withconst staticin the class and directly initialized, while - floating-point members such as
floatanddoublecan not.
This confuses me a lot.
Well, as a matter of fact,
static const doublemembers can be initialized in the class—if you declare theminline. If the value you want to initialize it to also happens to be a constant expression, then you can declare itconstexpr, in which case you do not need to declare itinlinebecause astatic constexprdata member is automatically inline.However, when a
static const doublemember is not inline, then it means that exactly one translation unit is responsible for supplying the definition of that member, and the definition is responsible for the initialization. Because a class definition needs to be#included into every translation unit that wants to access members of that class, it means the declaration of the member inside the class should not be a definition (because that would lead to multiple definitions). As a result, you must provide a single definition of the static member somewhere outside the class, and that single definition is the one that is responsible for initializing it.