Why aren't static const floats allowed?

后端 未结 6 2206
无人及你
无人及你 2020-11-29 02:25

I have a class which is essentially just holds a bunch of constant definitions used through my application. For some reason though, longs compile but floa

6条回答
  •  悲&欢浪女
    2020-11-29 03:21

    To answer the actual question you asked: "because the standard says so".

    Only variables of static, constant, integral types (including enumerations) may be initialized inside of a class declaration. If a compiler supports in-line initialization of floats, it is an extension. As others pointed out, the way to deal with static, constant, non-integral variables is to define and initialize them in the class's corresponding source file (not the header).

    C++ Standard Section 9.2 "Class Members" item 4:

    A member-declarator can contain a constant-initializer only if it declares a static member (9.4) of const integral or const enumeration type, see 9.4.2.

    Section 9.4.2 "Static Data Members" item 2:

    If a static data member is of const integral or const enumeration type, its declaration in the class definition can specify a constant-initializer which shall be an integral constant expression (5.19). In that case, the member can appear in integral constant expressions. The member shall still be defined in a namespace scope if it is used in the program and the namespace scope definition shall not contain an initializer.

提交回复
热议问题