为什么这个常量字符*在实际修改后无法修改?
How come this const char* can't be modified after actually modifying it?
以此示例:
int main()
{
const char* what = "Is This";
what = "Interesting";
cout << *what;
what[3] = 'a'; // Sytax Error: expression must be a modifiable lvalue
cout << *what;
return 0;
}
所以我将what
声明为const char*
,并且我能够将其重新分配另一个值(内存中的实际数据 - 不是内存地址本身)。
但是,它告诉我我无法更改第四位置的角色!
为什么?
在此代码中, what
是const char。
您可以更改what
,但是您不能更改*what
。
如果要声明指向const char的const指针,则需要两次编写const
:
const char *const what = "Is This";
// what is const
what = "Interesting"; // Error
// *what is also const
what[4] = 'x'; // Error
如果您想要const指针指向非const char,请在另一个地方写下:
char isthis[] = "Is This";
char interesting[] = "Interesting";
char *const what = isthis;
// what is const
what = interesting; // Error
// *what is not const
what[4] = 'x'; // Ok
const
适用于指向指针本身的字符!因此,您可以指出所需的任何C弦,但不能更改这些字符串的性格。
为示例的简单起见,我将使用另一种类型来说明该点(C-strings文字无法修改):
您实际上有类似的东西
const int i = 666;
const int j = 999;
const int *pi = &i;
pi = &j;
// *pi=444; is invalid, can't change the int pointed by pi
您可以构建一个无法更改的指针,但插入了:
int i = 666;
int j = 999;
int *const pi = &i;
*pi = 999;
// pi = &j; is invalid, pi will always point to i
然后您可以混合两者,切勿更改指针或插入率:
const int i = 666;
const int j = 999;
const int *const pi = &i;
// pi = &j; is invalid
// *pi = 444; is invalid
相关文章:
- 为什么我可以通过引用修改常量返回
- 通过非常量引用参数修改常量引用参数
- 如何在使用 Qt5 构造函数时将非常量参数修改为常量参数?
- 未定义的对象(〔basic.life〕/8):为什么允许引用重新绑定(和常量修改)
- 我们如何修改常量变量的值
- 当原始数据是常量时,修改指针指向的位置是 UB 吗?
- c++ 是否提供了一种使整个结构常量(不可修改)的方法?
- 以简单的方式修改常量字符 * 与字符 * 内容
- 如何在另一个成员函数中修改具有常量返回类型的成员函数的返回值
- 通过const_cast修改常量 std::vector 的元素<T>
- 为什么常量变量是可修改的?
- 可修改的右值和常量右值有什么区别?
- 非常量指针是否可以修改常量变量int c++
- 如何修改常量int值c++
- 修改常量对象
- 修改常量函数中的非常数属性
- 尝试修改常量引用
- 为什么在C++允许从外部修改常量对象的指针成员变量的内存?
- 如何修改常量的私有成员
- 通过中断修改常量引用