使用reinterpret_cast的危险

时间:2024-10-22 22:08:02

关键字: 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() = ;
virtual void func2() = ;
}; 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 ;
}