More Effective C++之类型转换

1.条款之优先考虑C++风格的类型转换

C++通过引用4种新的类型转换克服了C风格的类型转换的缺点。这四种操作符是:static_cast,const_cast,dynamic_cast以及reinterpret_cast。大多数情况下,关于这些操作符应该知道的是,我们所习惯的写法为:(type) expression

现在我们通常写为:static_cast<type> expression

(1)关于static_cast的使用:用于类型转换

比如之前:int  Number;

double result =(double) Number;

使用新的类型转换,我们应该这样写:

double result = static_cast<double> Number;

(2)关于const_cast的使用:用来去除一个表达式的const属性或volatile属性

例:

class Widget{....};

class SpecialWidget:public Widget{....};

void update(SpecialWidget *psw);

SpecialWidget sw;

const SpecialWidget &csw = sw;

update(&csw);  //这是错的,因为csw为const

update(const_cast<SpecialWidget *>(&csw));   //这是对的,使用了const_cast转换符

(3)关于dynamic_cast的使用:它是用来针对一个继承体系做向下或横向的安全转换

例:

(参考以上的代码接下面的代码实现)

Widget *pw;

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

(4)关于reinterpret_cast的使用:它最常见的用法是用在函数指针之间进行类型转换。

例:

typedef void (*FuncPtr)();

FuncPtr funcPtrArray[10];

int doSomething();  //把一个指向下面这个函数的指针放进funcPtrArray

funcPtrArray[10] = &doSomething;   //错误,类型出错

funcPtrArray[0]=reinterpret_cast<FuncPtr>(doSomething);   //正确,使用reinterpret_cast进行转换

参考文献《More Effective C++》作者:Scott Meyers  翻译:刘晓伟

猜你喜欢

转载自blog.csdn.net/Gaodes/article/details/82847084