static_cast, reinterpret_cast, const_cast和dynamic_cast

来源:互联网 发布:初级程序员证书 编辑:程序博客网 时间:2024/05/21 06:49
1, static_cast和reinterpret_cast (reinterpret_cast更像是C以前的强制转换)
C++中的static_cast一般执行非多态的转换;
而reinterpret_cast能将数据以二进制存在形式的重新解释,能够完成static_cast不能完成的转换。
例如:
int i, k;int* j = &k;i = (int)j;        //OK!i = reinterpret_cast<int>(j);    //OK!
i = static_cast<int>(j);        //Error!
======================================================================
2,const_cast类型转换:将const类型转为非const类型用只能用它,其他的转换都不行。
    const int b = 2;int* a;a = static_cast<int*>(&b);     //Error! 
a = reinterpret_cast<int*>(&b); //Error!
a = const_cast<int*> (&b); //OK!
 ======================================================================
3, dynamic_cast把基类指针类型转换成子类的类型
CBase* pBase = NULL;
pBase = new CBase();
CDerived* pDerived = dynamic_cast<CDerived*>(pBase);

总结:上诉的转换将原先的C强制转换分的更细了,减少出错的概率。