【问题标题】:Why this c++ code will not occur an error for the const [duplicate]为什么这个 c++ 代码不会发生 const 错误 [重复]
【发布时间】:2016-05-21 11:08:03
【问题描述】:
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 : %s\n", s1 );
delete[] s1;

我很困惑

const char* s3 = "likes";
s3 = "allows";

因为我认为 s3 是一个常量,所以它不能改变。但是,当s3 = "allows" 时,它可以工作。为什么?

【问题讨论】:

标签: c++ constants


【解决方案1】:

我认为 s3 是一个常量

不,s3 本身不是 const,它是指向 const 的指针,所以 s3 = "allows"; 没问题,而 *s3 = 'n'; 会失败。

如果你的意思是 const 指针,char* const s3const char* const s3 都是 const 指针,那么 s3 = "allows"; 就会失败。

总结(注意const的位置)

char* s3 是指向非常量的非常量指针,s3 = "allows";*s3 = 'n'; 都可以。
const char* s3 是指向 const 的非常量指针,s3 = "allows"; 可以,*s3 = 'n';失败。
char* const s3 是指向非 const 的 const 指针,s3 = "allows"; 失败,*s3 = 'n'; 很好。
const char* const s3 是指向 const 的 const 指针,s3 = "allows";*s3 = 'n'; 都会失败。

Constness of pointer

【讨论】:

  • 真的帮了我很多。非常感谢。
猜你喜欢
  • 2018-04-19
  • 2016-02-08
  • 1970-01-01
  • 1970-01-01
  • 2013-05-01
  • 1970-01-01
  • 2017-10-14
  • 2016-07-10
相关资源
最近更新 更多