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

一、C风格类型转换

char* staticStr = "Hello World";
int* intArray = (int*)staticStr;

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

 

二、C++类型转换运算符

1. static_cast

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

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

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

2. dynamic_cast

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

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

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

3. reinterpret_cast

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

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

4. const_cast

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

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。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值