为什么此 c++ 代码不会发生 const 的错误

Why this c++ code will not occur an error for the const

本文关键字:const 错误 c++ 代码 为什么      更新时间:2023-10-16
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 s3const 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';都将失败。

请参阅指针的恒定性。

相关文章: