为什么此 c++ 代码不会发生 const 的错误
Why this c++ code will not occur an error for the const
char* s1 = new char[30];
char s2[] = "is not";
const char* s3 = "likes";
s3 = "allows";
strcpy( s2, s3 );
sprintf( s1, "%s %s %s using functions.", "C++", s2, "fast code" );
printf( "String was : %sn", s1 );
delete[] s1;
我很困惑
const char* s3 = "likes";
s3 = "allows";
因为我认为 s3 是一个常量,所以它不能改变。但是,当s3 = "allows"
它起作用时。为什么?
我认为 s3 是一个常量
不,s3
不是 const 本身,它是指向 const 的指针,所以s3 = "allows";
很好,*s3 = 'n';
会失败。
如果你的意思是常量指针,char* const s3
和const char* const s3
都是常量指针,那么s3 = "allows";
就会失败。
总结(注意const
的位置)
char* s3
是指向非常量非常量的非常量指针,s3 = "allows";
和 *s3 = 'n';
都可以。
const char* s3
是指向 const 的非常量指针,s3 = "allows";
正常,*s3 = 'n';
失败。
char* const s3
是指向非常量常量的常量指针,s3 = "allows";
失败,*s3 = 'n';
就可以了。
const char* const s3
const 指针指向 const,则s3 = "allows";
和*s3 = 'n';
都将失败。
请参阅指针的恒定性。
相关文章:
- 在运算符重载定义中使用成员函数(const错误)
- 在函数中使用 const int size 参数创建数组会在 Visual Studio 中抛出错误 C++:表达式的计
- 需要帮助在 c++ 中将字符串转换为字符 ----错误 "const char *" 类型的值不能用于初始化 "char" 类型的实体
- 类型为 "Bucket&"(未限定的 const 限定)的引用不能使用 "SortedList." 类型的值进行初始化 如何修复此错误?
- 在gcc中意外调用了Const重载.编译器错误或兼容性修复程序
- 在其他容器中使用 boost::container::static_vector 时,GCC 编译错误"将'const s'绑定到类型's&'的引用丢弃限定符"
- 为什么我的编译器在调用 const getter 函数时抛出"转换丢失(const)限定符"错误?
- C++ 错误:由于 swprintf 而从 'int' 到 'const wchar_t* 的转换无效
- test1.cpp:9:77:错误:对"(const std::normal_distribution) <double>(std::mt19937&)"的调用不匹配
- 错误:对类型 'const ItemInstance' 的引用无法绑定到类型 'void' 的右值
- 错误:从'void*'到'const uint8_t* {aka const unsigned char*}'的转换无效 [-允许]
- C++ Boost - 序列化错误 - 将"const B"作为"this"参数
- 错误:从 'char' 到 'const char' [-允许] strcat(加密,密钥[i])的转换无效;
- 索引 2D 向量时'Reference to type const..'编译错误
- 引发"char const*"错误的实例后调用的终止
- 在返回 const 错误的函数中传递值
- 在c++包装的C代码中重复const错误
- 静态常量匿名联合使用 GCC 4.9.3 给出"uninitialized const"错误
- 将const char*传递给方法,但得到char const *错误
- 在' const '错误之前预期的主表达式