boost polymorphic_cast 进行多态转换

//由多继承导致的向下转换,及交叉转换
//最好使用  polymorphic_cast<>()
#include <cstdlib>
#include <vector>
#include <iostream>
using namespace std;
#include <boost/cast.hpp>
using namespace boost;
class Base1
{
public:
  virtual void print(){cout<<"Base1.print()"<<endl;}
  virtual ~Base1(){cout<<"Base1 析构"<<endl;}
};
class Base2
{
public:
  void Sing(){cout<<"Base2 is singging!"<<endl;}
  virtual ~Base2(){cout<<"Base2 析构"<<endl;}
};
class Derived:public Base1,public Base2
{
public:
  void DerivedPrint(){cout<<"Derived.DerivedPrint()"<<endl;}
  virtual void print(){cout<<"Derived.print()"<<endl;}
  void Sing(){cout<<"Derived is singging!"<<endl;}
};
void Do()
{
  cout<<"-----------------------------"<<endl;
  Base1* p = new Derived;
  p->print();
  try{
    Derived* pd = polymorphic_cast<Derived*>(p);
    pd->DerivedPrint();
    pd->Sing();
    Base2* p2 = polymorphic_cast<Base2*>(p);
    p2->Sing();
    int* pVoid = new int;
    //Base2* p3 = polymorphic_cast<Base2*>(pVoid);//这个转换是编译不过的
  }
  catch(std::bad_cast&e)
  {
    cout<<e.what()<<endl;
  }
  cout<<"-----------------------------"<<endl;
}
int main(int argc, char *argv[])
{
    Do();
    system("PAUSE");
    return EXIT_SUCCESS;
}

polymorphic_cast 和 dynamic_cast 的比较

//由多继承导致的向下转换,及交叉转换
//最好使用  polymorphic_cast<>()
#include <cstdlib>
#include <vector>
#include <iostream>
using namespace std;
#include <boost/cast.hpp>
using namespace boost;
class Base1
{
public:
  virtual void print(){cout<<"Base1.print()"<<endl;}
  virtual ~Base1(){cout<<"Base1 析构"<<endl;}
};
class Base2
{
public:
  void Sing(){cout<<"Base2 is singging!"<<endl;}
  virtual ~Base2(){cout<<"Base2 析构"<<endl;}
};
class Derived:public Base1,public Base2
{
public:
  void DerivedPrint(){cout<<"Derived.DerivedPrint()"<<endl;}
  virtual void print(){cout<<"Derived.print()"<<endl;}
  void Sing(){cout<<"Derived is singging!"<<endl;}
};
void polymorphic_cast_sample(Base1* p)
{
    Derived* pd = polymorphic_cast<Derived*>(p);//不用判断,如果错误自动抛出异常
    pd->DerivedPrint();
    pd->Sing();
    Base2* p2 = polymorphic_cast<Base2*>(p);//不用判断,如果错误自动抛出异常
    p2->Sing();
}
void dynamic_cast_sample(Base1* p)
{
    Derived* pd = dynamic_cast<Derived*>(p);
    if(!pd)throw std::bad_cast();//必须要手动判断一下,否则将会使用空指针
    pd->DerivedPrint();
    pd->Sing();
    Base2* p2 = dynamic_cast<Base2*>(p);
    if(!p2)throw std::bad_cast();//必须要手动判断一下,否则将会使用空指针
    p2->Sing();
}
void Do()
{
  cout<<"-----------------------------"<<endl;
  Base1* p = new Derived;
  p->print();
  try{
    polymorphic_cast_sample(p);
    cout<<"-----------------------------"<<endl;
    dynamic_cast_sample(p);
  }
  catch(std::bad_cast&e)
  {
    cout<<e.what()<<endl;
  }
  cout<<"-----------------------------"<<endl;
}
int main(int argc, char *argv[])
{
    Do();
    system("PAUSE");
    return EXIT_SUCCESS;
}

你可能感兴趣的:(System,Class)