c – 为什么我不能在指派的右侧放一个指向const的指针?

前端之家收集整理的这篇文章主要介绍了c – 为什么我不能在指派的右侧放一个指向const的指针?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
为什么我不能把const int * cp1放在作业的右手边?请看这个例子
  1. int x1 = 1;
  2. int x2 = 2;
  3.  
  4. int *p1 = &x1;
  5. int *p2 = &x2;
  6.  
  7. const int *cp1 = p1;
  8.  
  9. p2 = p1; // Compiles fine
  10.  
  11. p2 = cp1; //===> Complilation Error

为什么在指定的位置收到错误?毕竟我没有试图去
改变一个恒定的值,我只是试图使用一个常量值.

我在这里遗漏了一些东西

解决方法

After all I am not trying to change a constant value

不能允许从“指针到const”到“指向非const”的指针的隐式转换,因为这样可以改变常量值.想想下面的代码

  1. const int x = 1;
  2. const int* cp = &x; // fine
  3. int* p = cp; // should not be allowed. nor int* p = &x;
  4. *p = 2; // trying to modify constant (i.e. x) is undefined behavIoUr

BTW:对于您的示例代码,使用const_cast将很好,因为cp1实际上指向非常量变量(即x1).

  1. p2 = const_cast<int*>(cp1);

猜你在找的C&C++相关文章