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

本文来自 https://stackoverflow.com/questions/1563897/c-static-constant-string-class-member

因为我用 BING 搜这个错误搜不到,因此记录下来,方便后人。

问题描述

错误的起因是我想在 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; _Alloc = std::allocator]'|

解决方法

方法一

该方法来自 SO 的最高赞回答
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.

方法二

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

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

更多方法

更多方法请看 SO 的讨论

你可能感兴趣的:(#,坎坷报错路)