为什么我不能在赋值的右侧放置指向const的指针?

Lae*_*han 10 c++ pointers const variable-assignment

为什么我不能放在const int *cp1作业的右边?请看这个样本

int x1 = 1;
int x2 = 2;

int *p1 = &x1;
int *p2 = &x2;

const int *cp1 = p1;

p2 = p1;    // Compiles fine

p2 = cp1;   //===> Complilation Error
Run Code Online (Sandbox Code Playgroud)

为什么我在指定位置出错?毕竟我不想 改变一个常量值,我只是试图使用一个常量值.

我在这里错过了一些东西.

son*_*yao 10

毕竟我不想改变一个恒定的值

不允许从"指针指向const"到"指向非const指针"的隐式转换,因为它可以更改常量值.考虑以下代码:

const int x = 1;
const int* cp = &x; // fine
int* p = cp;        // should not be allowed. nor int* p = &x;
*p = 2;             // trying to modify constant (i.e. x) is undefined behaviour
Run Code Online (Sandbox Code Playgroud)

顺便说一句:对于你的示例代码,使用const_cast会很好,因为事实上cp1指向非const变量(即x1).

p2 = const_cast<int*>(cp1);
Run Code Online (Sandbox Code Playgroud)