Dynamic_cast

// 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;
}

 

阅读更多
文章标签: output iostream class
个人分类: VC
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

Dynamic_cast

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭