C++中的强制类型转换:static_cast、reinterpret_cast、dynamic_cast、const_cast

来源:互联网 发布:海奇软件怎么样 编辑:程序博客网 时间:2024/05/20 17:42

     C语言中的强制类型转换就是TYPE a = (TYPE)b;将b强制转换为TYPE类型。而C++中有四个特有的强制类型转换方法:static_cast、reinterpret_cast、dynamic_cast、const_cast。

   static_cast:静态类型转换,如将int 类型转换成char类型。 static_cast做强制类型转换时,C++编译器会做类型检查,在C语言中能用隐式转换的,在C++中都可以用static_cast进行强制类型转换,因为C++编译器类型检查都会通过。

int main(){    double num1=3.1415926;    int num2=static_cast<int>(num1);}

reinterpret_cast:重新解释类型。

在C语言中不同的指针类型之间是无法通过隐式转换的。这个时候在C++中就可以用reinterpret_cast,例如:

int main(){    char *p1="Hello world";    int *p2=reinterpret_cast<int *>(p1);    cout<<p1<<endl;    cout<<p2<<endl;}
输出结果p1是字符串Hello world,p2的值是指针本身的值。

dynamic_cast:从命名上理解是动态类型转换,如子类和父类之间的多态类型转换。可以用dynamic_cast把子类转换成父类,也可以把父类转换成子类。两个不相关的类也可以用dynamic_cast进行类型转换。例如:

#include<iostream>using namespace std;class Animal{public:    virtual void bark()=0;};class Dog:public Animal{public:    virtual void bark(){        cout<<"WANGWANG"<<endl;    }    void Dog_Eating(){        cout<<"I eat bone"<<endl;    }};class Cat:public Animal{public:    virtual void bark(){        cout<<"MIAOMIAO"<<endl;    }    void Cat_Eating(){        cout<<"I eat fish"<<endl;    }};void Play(Animal *test){    test->bark();    //dynamic_cast 能运行时进行类型识别    //父类对象转为子类对象,也就是向下转型,如果转换失败,则dog为NULL    Dog *dog = dynamic_cast<Dog*>(test);      if(dog!=NULL){        dog->Dog_Eating();  //让Dog去做自己特有的工作    }    Cat *cat=dynamic_cast<Cat*>(test);    if(cat!=NULL){        cat->Cat_Eating();//让Cat去做自己特有的工作    }}class man{    virtual void eat(){        cout<<"i eat orange"<<endl;    }};int main(){    Dog dog;    Cat cat;    Animal *animal=NULL;    Play(&dog);    Play(&cat);    animal = &dog;    animal=static_cast<Animal*>(&dog);    animal=dynamic_cast<Animal*>(&dog);    {        man temp;        //animal=static_cast<Animal*>(&temp);    //编译器会报错        animal=dynamic_cast<Animal*>(&temp);  //将man类转换成Animal类,编译通过    }    system("pause");       reutrn 0;}

其实,也可以用static_cast进行子类和父类之间的类型转换,但是因为static_cast无法进行动态类型检查,所以是不安全的。

const_cast:字面上理解就是去掉原来的const属性。例如:

#include<iostream>using namespace std;void print(const char* buffer){char *temp=NULL;temp=const_cast<char *>(buffer);temp[1]='2';  //输出结果是H2llo world,即借助temp完成对buffer内容的修改。也相当于把const属性去掉cout<<buffer<<endl;}int main(){char buffer[]="Hello world";//要保证buffer所指向的内存空间可以被修改,如果不能被修改,程序运行时会中断。/*char *p="Hello world";print(p);这两句运行的时候会出错,因为这个时候p所指向的内存空间是一个常量,不可以被修改*/       print(buffer);system("pause");return 0;}

我们编程的时候要清楚变量原来是什么类型,要转换成是什么类型,类型转换后有什么后果。









0 0
原创粉丝点击