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 为什么在指定的位置收到错误?毕竟我没有试图去 我在这里遗漏了一些东西 解决方法
不能允许从“指针到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:对于您的示例代码,使用 p2 = const_cast<int*>(cp1); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |