zoukankan      html  css  js  c++  java
  • 使用reinterpret_cast的危险

    关键字: c++ cast

    // Cast.cpp : Defines the entry point for the console application.
    //
    
    #include "stdafx.h"
    #include <iostream>
    
    using namespace std;
    
    class Base
    {
    public:
    
        virtual void func1() = 0;
        virtual void func2() = 0;
    };
    
    class A
    {
        virtual void func3();
    };
    
    void A::func3()
    {
        cout<<"func3"<<endl;
    }
    
    class B : public A, public Base
    {
    public:
        virtual void func1();
        virtual void func2();
    };
    
    void B::func1()
    {
        cout<<"func1"<<endl;
    }
    
    void B::func2()
    {
        cout<<"func2"<<endl;
    }
    
    
    void DynamicCast()
    {
        A* pA = new B();
        Base* pBase = dynamic_cast<Base*>(pA);//Work fine
        pBase->func1();
        pBase->func2();
    }
    
    void StaticCast()
    {
        A* pA = new B();
        //Base* pBase = static_cast<Base*>(pA);//Compiler error
        //pBase->func1();
        //pBase->func2();
    }
    
    void ReinterpretCast()
    {
        A* pA = new B();
        Base* pBase = reinterpret_cast<Base*>(pA);
        pBase->func1();
        pBase->func2();//run-time error: Access violation
    }
    
    int _tmain(int argc, _TCHAR* argv[])
    {
        DynamicCast();
        ReinterpretCast();
    
        return 0;
    }
  • 相关阅读:
    md5加密(4)
    生成短的uuid
    九九乘法
    闰年判断
    初识网络传输
    省选模拟77
    省选模拟76
    省选模拟75
    省选模拟74
    省选模拟73
  • 原文地址:https://www.cnblogs.com/ldlchina/p/3608456.html
Copyright © 2011-2022 走看看