effective c++ 条款27 minimize casting

  casting:

      old style:

int a = int (b);//b is double
int a = (int) b; // b is double 

 new cast:

  

const_cast<T>(expression)
dynamic_cast<T>(expression)
reinterpret_cast<T>(expression)
static_cast<T>(expression)

const_cast: cast away constness

dynamic_cast: safe downcasting, can be costy

reinterpret_cast: eg. pointer to int to int, rare used

static_cast: implicit conversions e.g. int to double

 

//static_cast
int x,y;
double b = static_cast<double>(x)/y;

//dynamic_cast
//normally we use this casting method, because we want to use the feature of derived class but we only have base class point at hand.

class Window
{};

class SpecialWindow: public Window
{
   void SpecialWindowFunc();
};

//say we only have pointer to window but it is special window
SpecialWindow swindow;
Window *pwin =  &swindow;
//say we want to use SpecialWindowFunc
dynamic_cast<SpecialWindow *>swindow->SpecialWindowFunc();

 

posted @ 2014-07-11 03:08  williamwood  阅读(122)  评论(0编辑  收藏  举报