c++ static_cast,const_cast,reinterpret_cast,dynamic_cast

来源:互联网 发布:鼠标 淘宝店推荐 编辑:程序博客网 时间:2024/05/20 01:13

static_cast

 

void test1()
{
        int f=3,s=2;
        double r = static_cast<double>(f)/s;
        cout<<r<<endl;
}

 

const_cast

从表达式去除const 属性

void test1()
{
           class B
        {
                public:
                        int m_i;
        };

        B b0;
        b0.m_i = 100;
        const B b1 = b0;

        //b1.m_i = 200;
        cout<<b0.m_i<<" "<<b1.m_i<<endl;

        const_cast<B&>(b1).m_i = 300;

        cout<<b0.m_i<<" "<<b1.m_i<<endl;

}

 

reinterpret_cast

 

void test1()
{
        int n = 9;
        double d = static_cast<double>(n);
        cout<<n<<" "<<d<<endl;

        double dd = reinterpret_cast<double &>(n);
        cout<<n<<" "<<dd<<endl;
}

 

dynamic_cast

在运行时检查,用于继承关系中

不是强制转换,带有某种咨询性质


void test1()
{
        class B{};
        class C:public B{};
        class D:public C{};

        D* pd = new D;
        C* pc = dynamic_cast<C*>(pd);
        B* pb = dynamic_cast<B*>(pd);
        void *p = dynamic_cast<C*>(pd);

        C *pc1 = pd;
        B *pb1 = pd;
        void *p1 = pd;

 

}

 

 

 

 

 

 

 

 

 

 

 


 

0 0
原创粉丝点击