我正在学习 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/