c++四种类型转换运算符详解

1.C风格类型转换
char* staticStr = "Hello World";
int* intArray = (int*)staticStr;

        这种类型转换是不安全的,C++编程应该尽量使用C++的类型转换运算符

2.C++类型转换运算符
  • static_cast

    static_cast 用于在相关类型的指针之间进行转换,还可以显示的执行标准数据类型的类型转换。例如

Base* objBase = new Derived();
Derived* objDer = static_cast<Derived*> (objBase); // 向下转化

    向上转换无需使用任何类型转换运算符。不过使用 static_cast 可让代码阅读者注意到这里使用了类型转换。

  • dynamic_cast

    用于运行阶段的类型识别。例如

destination_type* Dest = dynamic_cast<class_type*>(Srouce);
if(Dest) // Check for success of the casting operation
    Dest->CallFunc ();

    这里务必检查 dynamic_cast 的返回值,看它是否生效。如果返回值是NULL,说明转换失败。

  • reinterpret_cast
Base* objBase = new Base();
Unrelated* notRelated = reinterpret_cast<Unrelated*>(objBase);

    将一种对象类型转换为另一种,不管它们是否相关。应当尽量避免使用这种类型转换。

  • const_cast

    使用 const_cast 可以让程序猿关闭对象的 const 访问修饰符。例如

void displayAllData (const SomeClass* data) {
    // data->disPlayMembers(); Error: attempt to invork a non-const function!
    SomeClass* pCastedData = const_cast<SomeClass*>(data);
    pCastedData->displayMembers();
}

最后:当你确信指向的是 Derived 对象,可使用 static_cast 提高运行性能,而不需要使用 dynamic_cast。

猜你喜欢

转载自blog.csdn.net/afei__/article/details/80301319