dynamic_cast,static_cast repreint_cast const_cast

dynamic type:

  比如

  

class A {

};

class B : public A { };


B l;
A& k = l;

Here k is a reference to an object of type A, but the real type of the referred object, its dynamic type, is B.

Here "dynamic" has the meaning of "known only at run-time".

 

所以根据文档:

  dynamic_cast会进行动态类型检查,只有符合运行时类型的对象才能转换,转换失败会返回NULL(*)或者抛异常std::bad_cast.(&),而static_cast不会检查类型正确性。

  dynamic_cast 可以classes up, down, and sideways along the inheritance hierarchy.

  B* a = dynamic_cast <B*>l; // correct

  B b = B;

  B* a = dynamic_cast <B*>; // return null

 

static_cast 就像c风格的强制类型转换(int)一样,repreint_cast用于指针转换,也和c风格很相似,const_cast用于将类型的const性去掉或装上,但是将原本是const的对象转成const的行为是未定义的,由程序员自己把控。

 
posted @ 2017-12-01 00:45  shinymood  阅读(162)  评论(0编辑  收藏  举报