这是我的问题,问题在评论中
const int a = 5;
const_cast<int&>(a)=7; //throw over const attribute in a,and assign to 7
std::cout<<a<<std::endl; //why still out put 5!!!!!!!!!!
谁能告诉我原因,并推荐一些解决这些问题的书籍?
谢谢!
按照书面形式,您执行此操作的方式是未定义的行为。如果你想看看效果const_cast<>
以定义的方式:
int a = 5; // note: not const. regular object.
const int& cref = a; // const-reference to same object.
cref = 7; // illegal. cref is a const reference.
const_cast<int&>(cref) = 7; // legal. the original object a is not const.
The only这是定义行为的原因是由于原始变量的非常量性质,a
。你不能采取彻底的constobject并简单地抛弃常量,这就是您发布的代码所做的。 (至少已经多次向我解释过)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)