error: in-class initialization of static data member * of non-literal type
阿新 • • 發佈:2018-12-18
本文來自 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 的討論