尽量使用C++风格的类型转换

来源:互联网 发布:全国行政区域编码数据 编辑:程序博客网 时间:2024/05/17 11:56

四个操作符:static_cast,const_cast,dynamic_cast和reinterpret_cast

在大多数情况下,对于这些操作符你只需要知道原来你习惯于这样写:

(type)expression

而现在你总应该这样写:

static_cast <tyep> (expression)

假设你想把int转换成double,以便让包含int类型的变量的表达式产生出浮点数值的结果。

如果用C风格的类型转换,你能这样写:

int firstNumber,secondNumber;


double result =((double)firstNumber/secondNumber;


如果用上述新的类型转换方法,你应该这样写:

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


功能限制

不能用static_cast象用C风格的类型转换一样把struct转换为int类型或者把double

转换为指针类型,另外,static_cast不能从表达式中去除const属性,因为新的类型操作符

const_cast有这样的功能.


如果你试图使用const_cast来完成修改constness或者volatileness属性之外的事情,

你的类型转换将被拒绝

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

//函数中能被更新


update((specialWidget*)&csw);

//错误!不能传递一个const SpecialWidget* 变量

//给一个处理SpecialWidget*类型变量的函数

update(const_cast<SpecialWidget*>(&csw));

//正确,csw的const被显示地转换掉(

//csw和sw两个变量值在update

//函数中能被更新

update((specialWidget*)&csw);

//同上,但用了一个更难识别的C风格的类型转换


Widget* pw=new SpecialWidget;

update(pw);    //错误,pw的类型是widget* ,但是

//update函数处理的是SpecialWidget*类型

update(const_cast<SpecialWidget*>(pw));

//错误!const_cast仅能被用在影响constness or volatileness的地方上。

//不能用在继承子类进行类型转换

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


第二种特殊的类型转换符是dynamic_cast,它被用于安全沿着类的继承关系向下进行类型转换

这就是说,你能用dynamic_cast把指向基类的指针或引用转换成指向其派生类或其兄弟类的指针或引用,而且你知道转换是否成功。

失败的转换将返回空指针(当对指针进行类型转换时)或者抛出异常(当对引用进行类型转换时)

Widget* pw;

...

update(dynamic_cast<SpecialWidget*)(pw));

//正确,传递给update函数一个指针

//是指向变量类型为SpecialWidget的pw的指针

//如果pw确实指向一个对象,否则传递过去的将使空指针.


void updateViaRef(SpecialWidget& rsw);

updateViaRef(dynamic_cast<SpecialWidget&>(*pw);

//正确。传递给updateViaRef函数

//SpecialWidget pw指针,如果pw确实指向某个对象

//否则将抛出异常

dynamic_casts在帮助你浏览继承层次上是有限制的。

它不能被用于缺乏虚函数的类型上,也不能用来转换掉constness:

int firstNumber,secondNumber;

...

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

//错误,没有继承关系

const SpecialWidget sw;

...

update(dynamic_cast<SpecialWidget*>(&sw));

//错误!dynamic_cast不能转换掉const。






0 0
原创粉丝点击