【问题标题】:C++ String literal and constantsC++ 字符串文字和常量
【发布时间】:2020-05-01 20:13:50
【问题描述】:

在问这个之前,我读了previous question,但问题有点不同。 我在课堂上使用这个:

static constexpr char* kSuffix = "tos";

使用 c++11 编译 gcc 时出现此错误:

error: ISO C++ forbids converting a string constant to 'char*' [-Werror=write-strings]

但是constexpr 是比const 更严格的约束,所以constexpr 必须是const,但反之则不然。所以我想知道为什么在这种情况下 gcc 无法识别constexpr

【问题讨论】:

标签: c++ string c++11 constants constexpr


【解决方案1】:

所以constexpr 必须是const

请注意,constexprkSuffix 本身上是合格的,因此指针变为 const(如 char* const),但指针不会变为 const(如 const char*)。 Gcc 只是想告诉你应该将kSuffix 声明为指向const 的指针,即

static constexpr const char* kSuffix = "tos";

【讨论】:

  • constexprkSuffix 上不合格吗?
  • @fluter 是的。我修改了答案,是不是更清楚了?
  • 我还是想知道为什么constexpr在这里代替了const,它们本质上处于相同的位置。
  • @fluter 最好将constexprconst 视为不同的东西;例如我们可以声明一个const 指针,如char* const 和一个指向const 的指针,如const char*,但我们只能写constexpr char*(或constexpr const char*),这意味着一个constexpr 指针。 (还要注意我们不能写像char* constexpr这样的东西。)
猜你喜欢
  • 2015-09-17
  • 1970-01-01
  • 1970-01-01
  • 2016-12-05
  • 2011-04-21
  • 1970-01-01
  • 2011-05-28
  • 2012-09-19
相关资源
最近更新 更多