为什么编译器让你"写"一个const变量在这里? [英] Why does compiler allow you to "write" a const variable here?

查看:88
本文介绍了为什么编译器让你"写"一个const变量在这里?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么样的欺骗编译器是这样的:

  const int的一个= 5;
*(为(int *)及一个)= 5; // VC /程序armcc不抱怨

在上面的这个删节等同的:

  const int的* ptr2const =安培; A;
为int * PTR = ptr2const; //预期错误在这里提出
* PTR = 5;


解决方案

C-风格的转换让你在你的例子抛弃常量性等。在C ++中,你通常会使用新风格的转换,如的static_cast<> ,它不允许你抛弃常量性。只有的const_cast<方式> 允许你这样做。

Why can you kind of cheat compiler this way:

const int a = 5;
*((int*)&a)=5;   // VC/armcc does not complain

when above is "abridged" equivalent of this:

const int *ptr2const = &a;
int *ptr = ptr2const;      // as expected error is raised here
*ptr = 5;

解决方案

C-style casts allow you to cast away constness like in your example. In C++, you would normally use the new style casts such as static_cast<>, which don't allow you to cast away constness. Only const_cast<> allows you to do that.

这篇关于为什么编译器让你&QUOT;写&QUOT;一个const变量在这里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆