为什么我不能把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
为什么在指定的位置收到错误?毕竟我没有试图去
改变一个恒定的值,我只是试图使用一个常量值.
我在这里遗漏了一些东西
解决方法
After all I am not trying to change a constant value
不能允许从“指针到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
BTW:对于您的示例代码,使用const_cast
将很好,因为cp1实际上指向非常量变量(即x1).
- p2 = const_cast<int*>(cp1);