C++,改变地址指针指向(指向一个常量值)

标签 c++ pointers constants declaration

我正在学习 const 指针和值,但是我遇到了赋值问题 ptr2 = &x,错误 C2440:“=”:无法从“const int *”转换为“int *”。为什么? ptr2 不是常量,所以我可以更改它指向的地址,x 是 const 但我不更改它的值。我很困惑。

const int x = 10;
int y = 20;
int * const ptr1 = &y; // const pointer must be initialized
int *ptr2 = &y;
cout << *ptr1 << endl;
*ptr1 = 5; // changes content of the address
cout << *ptr1 << endl;
ptr2 = &x; // changes address pointed to by ptr2,  not content of x!
cout << *ptr2 << endl;

最佳答案

const指针和const值的区别:

int * px; // pointer to an int
int * const px2; // constant pointer to an int
int const * px3; // pointer to a constant int
int const * const px4; // constant pointer to a constant int.

你的指针只能指向相同的类型,或者至少指向限制较少的类型。

int x = 1;
int const y = 2;
int const * px = &x; // fine, as const is more restrictive
int * py = &y; // Wrong -> you'd lose the const

所以,如果你有一个 const int,你的指针也必须是一个 const int。指针是否恒定是另一回事

关于C++,改变地址指针指向(指向一个常量值),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22252756/

相关文章:

c - 指向结构的空指针,使用宏访问元素

c++ - 同时接受const和非const参数的模板方法

c++ - 如何创建用于多个源文件的全局变量/包含/函数

c++ - 如何使用 UART 传输数据结构?

c++ - 为什么我不能在赋值的右侧放置一个指向 const 的指针?

c - 本地套接字选项集与指向套接字选项集的指针

输入对象没有 const 的 C++ 重载 << 会产生错误,该错误随 const 对象一起消失

c - 在 C 中,如何使常量仅对特定源文件可见?

c++ - 在 C++ 中使用引用变量的 void 返回类型

c++ - MFC 列表控件