c++ 38 RTTI ,dynamic_cast ,typeid

来源:互联网 发布:淘宝 日语 编辑:程序博客网 时间:2024/05/17 01:15

dynamic_cast 的用法

#include <iostream>#include <string>using namespace std;class Shape{  public:  virtual void Draw()=0;//只要有一个虚函数,这个类就是抽象类  而这里去掉virtual 则会调用基类Draw  /*void Draw() { cout<<"Shape Draw"<<endl; }*/  virtual ~Shape()//这样不回产生内存泄漏问题 会调用派生类析构函数,然后调用基类析构函数  {  cout<<"~Shape.."<<endl;  }  };  class Circle:public Shape  {  public:  void Draw()  {  cout<<"Circle Draw"<<endl;  }  ~Circle()  {  cout<<"~Circle"<<endl;  }  };  class Square:public Shape  {  public:  void Draw()  {  cout<<"Square Draw"<<endl;  }  ~Square()  {  cout<<"~Square"<<endl;  }  };  int main(){Shape* p;Circle c;p=&c;//基类指针指向派生类对象p->Draw();//掉用派生类虚函数if(dynamic_cast<Circle*>(p)){//运行时识别是Circle 对象 类型安全的向下转型。cout<<"p is point to a circle object"<<endl;Circle* cp=dynamic_cast<Circle*>(p);//安全向下转型cp->Draw();//这种方式 要比虚函数多态调用 大一些  要在编译器中开启一个选项//c++  语言  下 启动运行时类型信息//如果没有虚函数 是不允许的。  这两个显示 1,开启支持,2,virtual 函数}else if(dynamic_cast<Square*>(p)){cout<<"p is point to a Square object"<<endl;}else{ cout<<"p is point to other object"<<endl;}//static_cast 用在编译器认可的转型//reinterpret_cast 用在编译器 不可认的转型//const_cast 去除常量限定//dynamic_cast 安全的向下转型。return 0;}


type id

#include <iostream>#include <string>using namespace std;class Shape{  public:  virtual void Draw()=0;//只要有一个虚函数,这个类就是抽象类  而这里去掉virtual 则会调用基类Draw  /*void Draw() { cout<<"Shape Draw"<<endl; }*/  virtual ~Shape()//这样不回产生内存泄漏问题 会调用派生类析构函数,然后调用基类析构函数  {  cout<<"~Shape.."<<endl;  }  };  class Circle:public Shape  {  public:  void Draw()  {  cout<<"Circle Draw"<<endl;  }  ~Circle()  {  cout<<"~Circle"<<endl;  }  };  class Square:public Shape  {  public:  void Draw()  {  cout<<"Square Draw"<<endl;  }  ~Square()  {  cout<<"~Square"<<endl;  }  };  int main(){Shape* p;Circle c;p=&c;//基类指针指向派生类对象p->Draw();//掉用派生类虚函数if(dynamic_cast<Circle*>(p)){//运行时识别是Circle 对象 类型安全的向下转型。cout<<"p is point to a circle object"<<endl;Circle* cp=dynamic_cast<Circle*>(p);//安全向下转型cp->Draw();//这种方式 要比虚函数多态调用 大一些  要在编译器中开启一个选项//c++  语言  下 启动运行时类型信息//如果没有虚函数 是不允许的。  这两个显示 1,开启支持,2,virtual 函数}else if(dynamic_cast<Square*>(p)){cout<<"p is point to a Square object"<<endl;}else{ cout<<"p is point to other object"<<endl;}//static_cast 用在编译器认可的转型//reinterpret_cast 用在编译器 不可认的转型//const_cast 去除常量限定//dynamic_cast 安全的向下转型。//typeid 运算符 返回的是type_info 对象//用在对象上      cout<<typeid(*p).name()<<endl;//打印的是class Circle  //指定类型上  cout<<typeid(Circle).name()<<endl;//打印的是class Circle  if(typeid(Circle).name()==typeid(*p).name())  {  cout<<"===p is point to a circle object===="<<endl;//Circle* cp=dynamic_cast<Circle*>(p);//安全向下转型//cp->Draw();  ((Circle*)p)->Draw();  }else if(typeid(Square).name()==typeid(*p).name())  {  cout<<"p is point to a Square object====="<<endl;  ((Square*)p)->Draw();  //reinterpret_caset 不作任何对齐操作  //() 还是会做一些对齐操作  }else{    cout<<"p is point to other object=="<<endl;  }  //通过type_id 也可以做到运行时类型识别return 0;}


0 0
原创粉丝点击