C++ 转换操作符

1、static_cast

  将一个值以符合逻辑的方式转型。这可以看做是"利用原值重建一个临时对象,并在设立初值时使用型别转换"。

  唯有当上述的型别转换有所定义,整个转换才会成功。所谓的“有所定义”,可以是语言内建规则,也可以是程序员自定的转换动作。

 1 #include<iostream>
 2 using namespace std;
 3 int main(){
 4     float x;
 5     x = 10.5;
 6     cout<<"float:"<<x<<endl;
 7     cout<<"int:"<<static_cast<int>(x)<<endl;
 8 }
 9 输出:
10 10.5
11 10

2、dynamic_cast

  将多态型别向下转型为其实际静态型别。这是唯一在执行期进行检验的转型动作。你可以用它来检验某个多态对象的型别。

  

 1 #include<iostream>
 2 using namespace std;
 3 class Car{
 4     virtual void fn(){}
 5 };
 6 class Carbriolet:public Car{
 7     virtual void fn(){}
 8 };
 9 class Limousine:public Car{
10     virtual void fn(){}    
11 };
12 void f(Car * cp){
13     Carbriolet *p = dynamic_cast<Carbriolet*>(cp);
14     if(p == NULL){
15         cout<<"p为空"<<endl;
16     }else{
17         cout<<"p为Carbriolet对象"<<endl;
18     }
19 }
20 int main(){
21     Carbriolet c;
22     Car car;
23     Limousine l;
24     f(&car);
25     f(&c);
26     f(&l);
27     return 0;
28 }
29 输出:
30 p为空
31 p为Carbriolet对象
32 p为空

3、const_cast

设定或去除型别的常数性,亦可去除volatile修饰词。

4、reinterpret_cast

reinterpret_cast运算符是用来处理无关类型之间的转换;它会产生一个新的值,这个值会有与原始参数(expressoin)有完全相同的比特位。

posted @ 2016-10-21 15:14  IT男汉  阅读(325)  评论(0编辑  收藏  举报