加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 03:06:06 所属栏目:百科 来源:网络整理
导读:为什么我不能把const int * cp1放在作业的右手边?请看这个例子 int x1 = 1;int x2 = 2;int *p1 = x1;int *p2 = x2;const int *cp1 = p1;p2 = p1; // Compiles finep2 = cp1; //=== Complilation Error 为什么在指定的位置收到错误?毕竟我没有试图去 改变一
为什么我不能把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);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读