在问这个问题之前,我读过 previous question ,但问题有点不同。 我在类里面使用这个:
static constexpr char* kSuffix = "tos";
使用 gcc 和 c++11 进行编译时出现此错误:
error: ISO C++ forbids converting a string constant to 'char*' [-Werror=write-strings]
但是 constexpr
是比 const
更严格的约束,因此 constexpr
必须是 const
,但是反之则不然。所以我想知道为什么 gcc 在这种情况下无法识别 constexpr
?
最佳答案
so a
constexpr
is must aconst
请注意,constexpr
在 kSuffix
本身上进行了限定,因此指针变为 const
(如 char* const
>),但被指向者不会变成 const
(如 const char*
)。 Gcc 只是想告诉你,你应该将 kSuffix
声明为指向 const
的指针,即
static constexpr const char* kSuffix = "tos";
关于C++ 字符串文字和常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59745024/