c++类型转换

const_cast最普通的用途就是转换掉对象的 const 属性。

class Widget { ... };
class SpecialWidget: public Widget { ... };
void update(SpecialWidget *psw);
SpecialWidget sw; // sw 是一个非 const 对象。
const SpecialWidget& csw = sw; // csw 是 sw的一个引用  它是一个 const 对象
update(&csw); // 错误!不能传递一个 const SpecialWidget* 变量  给一个处理 SpecialWidget*类型变量的函数
update(const_cast<SpecialWidget*>(&csw)); // 正确,csw的 const被显示地转换掉(  csw 和 sw 两个变量值在 update 函数中能被更新)

Widget *pw = new SpecialWidget;
update(pw); // 错误!pw的类型是 Widget*,但是

update(const_cast<SpecialWidget*>(pw)); // 错误!const_cast仅能被用在影响 // constness or volatileness 的地方上。// 不能用在向继承子类进行类型转换。

你能用 dynamic_cast把指向基类的指针或引用转换成指向其派生类或其兄弟类的指针或引用,而且你能知道转换是否成功。失败的转换将返回空指针(当对指针进行类型转换时)或者抛出异常(当对引用进行类型转换时) :

它不能被用于缺乏虚函数的类型上(参见条款 M24) ,也不能用它来转换掉 constness:

Widget *pw;
...
update(dynamic_cast<SpecialWidget*>(pw)); // 正确,传递给 update函数一个指针

如你想在没有继承关系的类型中进行转换,你可能想到 static_cast。如果是为了去除const,你总得用 const_cast。

int firstNumber, secondNumber; 

double result = static_cast<double>(firstNumber)/secondNumber; 

 

reinterpret_casts的最普通的用途就是在函数指针类型之间进行转换。

typedef void (*FuncPtr)(); // FuncPtr is 一个指向函数  的指针,该函数没有参数  返回值类型为 void
FuncPtr funcPtrArray[10]; // funcPtrArray 是一个能容纳  10 个 FuncPtrs 指针的数组

让我们假设你希望(因为某些莫名其妙的原因)把一个指向下面函数的指针存入funcPtrArray数组:

int doSomething(); 

你不能不经过类型转换而直接去做,因为 doSomething 函数对于 funcPtrArray 数组来说有一个错误的类型。在 FuncPtrArray 数组里的函数返回值是 void 类型,而doSomething
函数返回值是 int 类型。
funcPtrArray[0] = &doSomething; // 错误!
funcPtrArray[0] = reinterpret_cast<FuncPtr>(&doSomething);// reinterpret_cast可以让你迫使编译器以你的方法去看待它们:

 

 

 

 

posted on 2012-10-31 10:32  GIS-MAN  阅读(156)  评论(0编辑  收藏  举报

导航