C++ 字符串字面值
C++11后,字符串就不能像之前或者C语言中一样赋值给char *,下面的代码将会报warning或报错
char *s = "abc";
warning: ISO C++ forbids converting a string constant to ‘char*’
字符串字面值应该被当作const char*
类型,因为它们不可以被改变,任何尝试改变字面值的操作都会导致错误
因此解决的方法就是
const char *s = "abc";
char const *s = "abc";
或者直接cast也可以
char *s = (char *)"abc"; // 任何改变的尝试仍然会导致错误
上面的const char *
和char const *
其实都是指const char *
,另一种容易混淆的类型是char * const
,为了区分它们只需要将*读作pointer to,从右向左读即可
const char *p; // p is a pointer to const char
char * const p; // p is a const pointer to char
Reference
[1] https://stackoverflow.com/questions/20944784/why-is-conversion-from-string-constant-to-char-valid-in-c-but-invalid-in-c
[2] https://blog.csdn.net/yingxunren/article/details/3968800