error: in-class initialization of static data member * of non-literal type

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_41104353/article/details/84799805

本文来自 https://stackoverflow.com/questions/1563897/c-static-constant-string-class-member
因为我用 BING 搜这个 error 搜不到,因此记录下来,方便后人。

问题描述

错误的起因是我想在 C++ 的一个类中定义 static const string,并且给这个变量初始化:

class A {
   private:
      static const string RECTANGLE = "rectangle";
}

上面这个代码来自第一个链接。

然后就报错

error: in-class initialization of static data member 'const string Settings::ROOT_PATH' of non-literal type|
error: call to non-constexpr function 'std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::basic_string(const _CharT*, const _Alloc&) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]'|

解决方法

方法一

该方法来自 sof 的最高赞回答
You have to define your static member outside the class definition and provide the initializer there.
First

// In a header file (if it is in a header file in your case)
class A {   
private:      
  static const string RECTANGLE;
};

and then

// In one of the implementation files
const string A::RECTANGLE = "rectangle";

The syntax you were originally trying to use (initializer inside class definition) is only allowed with integral and enum types.

方法二

该方法来自 sof 的次高赞回答
In C++11 you can do now:

class A {
 private:
  static constexpr const char* STRING = "some useful string constant";
};

更多方法

更多方法请看 sof 的讨论

猜你喜欢

转载自blog.csdn.net/sinat_41104353/article/details/84799805
今日推荐