C++ 字符串文本和常量

C++ String literal and constants

本文关键字:常量 文本 字符串 C++      更新时间:2023-10-16

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

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

所以constexpr必须是一个const

请注意,constexpr是对kSuffix本身限定的,因此指针变为const(如char* const(,但指针不会变为const(如const char*(。gcc 只是想告诉你,你应该声明kSuffix为指向const的指针,即

static constexpr const char* kSuffix = "tos";