当前位置:编程学习 > C/C++ >>

细说C++类型转换操作符

C++语言虽然兼容C,也支持C语言的类型转换用法,就是将类型用圆括号括起来,这种转换可视性比较差,难以跟踪错误的转换。C++提供了命名的强制转换操作符,毕竟转换有时是不安全的,所以使用命名转换操作符可以根据所使用的转换操作符可以判断风险级别。

下面我们就来看看C++提供的四种命名的强制转换操作符的具体功能和用法。

1.const_cast

2.static_cast

3.reinterpret_cast

4.dynamic_cast

这四个操作符的使用方法是相同的,都是cast-name<Type>(expression),Type是被转换值expression的目标类型。

下面看看这四个操作符分别的应用场合。

1.const_cast

顾名思义,const_cast就是将表达式的const性质去掉,例如

[cpp] 
char* string_copy(char* s) 

    return s; 

int main() 

    const char* pc_str; 
    char* pc = string_copy(const_cast<char*>(pc_str));//如直接传入pc_str则编译错误 
    return 0; 

上例只是说明问题,并不实现功能。

要记住,const_cast只能用来添加或删除const特性,同时添加或删除特性也只能用const_cast。

2.static_cast

这个用途比较广泛,编译器隐式执行的任何类型转换都可以有static_cast完成。

另外,static_cast多用于将一个void*类型的指针强制转换为原来的指针类型,例如:


[cpp] 
double d = 12; 
void* p = &d; 
double* pd = static_cast<double*>(p); 
cout << *pd << endl; 
输出结果为12,说明转换后依然还是指向同一个地址。
3.reinterpret_cast

这个操作符很难看,也很难记,为什么呢,因为危险性比较大,设计成这个样子就是为了让我们尽量不用它,它用于对指针之间进行转换,例如:


[cpp] 
int* ip; 
char* pc = reinterpret_cast<char*>(ip); 
string str(pc); 
虽然可以编译通过,但是却会带来严重的运行时错误,所以,要尽量避免reinterpret_cast的使用。
4.dynamic_cast

dynamic_cast用于子类和父类之间的转换,它可以将父类的指针或引用转换为子类的指针或引用。

dynamic_cast与前三种强制转换不同,它涉及运行时类型检查。如果绑定到引用或指针的类型对象不是目标类型的对象时,则dynamic_cast失败。当用于指针的转换失败时,dynamic_cast的结果为0,用于引用的转换失败时,则抛出一个bad_cast异常。

可用下面例子所用的结构对转换进行检测:

指针转换:


[cpp] 
if(Derived *derviedPtr = dynamic_cast<Derived*>(basePtr){ 
    // use the Derived object to which derivedPtr points 

else{ 
    // basePtr oiubsts at a Base object 
    // use the Base object to which basePtr points 

引用转换:

[cpp] 
void f(const Base& b) 

    try{ 
        const Derived& d = dynamic_cast<const Derived&>(b); 
        // use the Derived object to which b referred 
    } 
    catch (bad_cast){ 
        // handle the fact that the cast failed 
    } 

至此,转换操作符介绍完毕。


作者:RO_wsy
补充:软件开发 , C++ ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,