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<char>; _Alloc = std::allocator<char>]'|

解决方法

方法一

该方法来自 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 的讨论

  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值