c++四种cast

#include <iostream>
using namespace std;
class Base
{
    public:
        Base():b(1){}
        virtual void fun(){};
        int b;    
};
class Son:public Base
{
    public:
        Son():d(2){}
        int d;    
};
int main(int argc, char *argv[])
{
    int n=97;
    int *p=&n;
    char *c=reinterpret_cast<char*> (p);//int指针转char指针 
    char *c2=(char*)(p);
    cout<<"reinterpret_cast输出:"<<*c2<<endl;
    const int *p2=&n;
    int *p3=const_cast<int*>(p2);//把常量指针转成非常量指针 
    *p3=100;
    const int &f=100;
    cout<<"f is "<<f<<endl; 
    int &f2=const_cast<int&>(f);//把常量引用转换成非常量引用 
    f2=30;
    cout<<"f2 is "<<f2<<endl;
    cout<<"const_cast输出:"<<*p3<<endl; 
    
    Base* b1=new Son;
    Base* b2=new Base;
    Son *s1=static_cast<Son*>(b1);//同类型转换
    Son *s2=static_cast<Son*>(b2);//下行转换,不安全
    cout<<s1->d<<endl;
    cout<<s2->d<<endl;//返回垃圾值 
    
    Son *s3=dynamic_cast<Son*>(b1); //同类型转换
    Son *s4=dynamic_cast<Son*>(b2);//下行转换,安全 ,返回nullptr 
    cout<<s3->d<<endl;
    if(s4==nullptr)
    {
        cout<<"s4指针为nullptr"<<endl;
    } 
    else{
        cout<<s4->d<<endl;
    }
    return 0;
}

 

posted @ 2022-03-03 11:19  菠萝超级酸  阅读(79)  评论(0编辑  收藏  举报