四种强制类型转换之一const_cast
Page 1 of 1
四种强制类型转换之一const_cast
const_cast
-可以在对象上设置const或消除const
-只有const_cast可以删除const属性
-为了安全性,const_cast只能用于指针,因为在指针之间是可以随意交换
如果你试图使用一个 const_cast 以外的新风格强制转型来代替const_cast,你的代码将无法编译。
int main()
{
const int * cp = new int; //const
*cp = 50; //error
int * p = const_cast(cp); //const_cast把cp转换去non-const
*p = 50; //ok!
const int * temp = const_cast(p); //const_cast又把p转回去const
*temp = 60; //error
return 0;
}
-可以在对象上设置const或消除const
-只有const_cast可以删除const属性
-为了安全性,const_cast只能用于指针,因为在指针之间是可以随意交换
如果你试图使用一个 const_cast 以外的新风格强制转型来代替const_cast,你的代码将无法编译。
int main()
{
const int * cp = new int; //const
*cp = 50; //error
int * p = const_cast
*p = 50; //ok!
const int * temp = const_cast
*temp = 60; //error
return 0;
}
too wei- Sponsor
- Posts : 31
Points : 66351
Reputation : 0
Join date : 2015-04-21
Age : 25
Location : Johor
Page 1 of 1
Permissions in this forum:
You cannot reply to topics in this forum
|
|