static const double cannot have an in-class initializer. why is it so?

前端 未结 3 1171
闹比i
闹比i 2020-12-24 01:34

The problem with the following code is static member of type "const double" cannot have an in-class initializer. Why is applicable only for a \'const double\'in th

3条回答
  •  Happy的楠姐
    2020-12-24 02:12

    The compiler offered me to use constexpr instead of const:

    static_consts.cpp:3:29: error: ‘constexpr’ needed for in-class initialization of static data member ‘const double sample::md’ of non-integral type [-fpermissive]
    static_consts.cpp:7:22: error: ‘constexpr’ needed for in-class initialization of static data member ‘const double sample::md’ of non-integral type [-fpermissive]
    

    I've just accepted the offer:

    class sample{
       static const char mc = '?';
       static constexpr double md = 2.2;
       static const bool mb = true;
    };
    const char sample::mc;
    const bool sample::mb;
    int main(){
    }
    

    And now it compiles just fine (C++11).

提交回复
热议问题