微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

为什么我不能把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);

原文地址:https://www.jb51.cc/c/112557.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐