简体   繁体   English

C++ 字符串字面量和常量

[英]C++ String literal and constants

Before asking this, I read previous question , but the issue is a bit different.在问这个之前,我阅读了上一个问题,但问题有点不同。 I'm using this in my class:我在课堂上使用这个:

static constexpr char* kSuffix = "tos";

Compiling with gcc with c++11 got me this error:用 c++11 编译 gcc 给了我这个错误:

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

But constexpr is a stricter constraint than const does, so a constexpr is must a const , but not vice versa.但是constexpr是比const更严格的约束,因此constexpr必须是const ,反之亦然。 So I wonder why is gcc not recognising constexpr in this case?所以我想知道为什么 gcc 在这种情况下不识别constexpr

so a constexpr is must a const所以constexpr必须是const

Note that the constexpr is qualified on kSuffix itself, so the pointer becomes const (as char* const ), but the pointee won't become const (as const char* ).请注意, constexprkSuffix本身上被限定,因此指针变为const (如char* const ),但指针不会变为const (如const char* )。 Gcc just wants to tell you that you should declare kSuffix as a pointer to const , ie gcc 只是想告诉你,你应该将kSuffix声明为指向const的指针,即

static constexpr const char* kSuffix = "tos";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM