// RTTI_CAST.cpp : Defines the entry point for the console application.
//
/// Summary:
/// There must have inheritress between Source type and target type.
/// if not, static_cast will bring compile error;
/// dynamic_cast will return false or throw exception.
#include <iostream>
using namespace std;
class A
{
public:
A(int j = 0): i(j)
{
}
virtual ~A() {}
virtual void Output()
{
cout<< i;
}
private:
int i;
};
class B : public A
{
public:
B() : A(1),j(2)
{
}
virtual ~B() {}
virtual void Output()
{
A::Output();
cout<< j<<endl;
}
private:
int j;
};
int _tmain(int argc, _TCHAR* argv[])
{
char a = 'a';
int * pI = static_cast<int*>(&a); // failed.
B b;
A* pA = dynamic_cast<A*>(&b);
pA->Output();
const type_info& aInfo = typeid(A);
const type_info& bInfo = typeid(B);
try
{
B* pB = dynamic_cast<B*>(pA);
pB->Output();
}
catch(bad_cast& e)
{
std::cout<<e.what()<<endl;
}
return 0;
}
本文通过C++示例代码展示了RTTI_cast的概念及其使用方法,包括如何利用static_cast和dynamic_cast进行类型转换,并演示了当目标类型不是源类型的派生类时可能出现的编译错误或运行时异常。
940

被折叠的 条评论
为什么被折叠?



