Runtime Type Information(融贯变通 RTTI)

用于知道程序执行中某物件属于那种类别:

例子如下:

 // RTTI.CPP - built by C:\> cl.exe -GR rtti.cpp <ENTER>
 #include <typeinfo.h>
 #include <iostream>
 #include <string.h>
using namespace std;

 class graphicImage
 {
 protected:
 char name[80];

 public:
 graphicImage()
 {
 strcpy_s(name, "graphicImage");
 }

 virtual void display()
 {
 cout << "Display a generic image." << endl;
 }

 char* getName()
 {
 return name;
 }
 };
 //---------------------------------------------------------------
 class GIFimage : public graphicImage
 {
 public:
 GIFimage()
 {
 strcpy_s(name, "GIFimage");
 }

 void display()
 {
 cout << "Display a GIF file." << endl;
 }
 };

class PICTimage : public graphicImage
{
 public:
 PICTimage()
 {
 strcpy_s(name, "PICTimage");
 }

 void display()
 {
 cout << "Display a PICT file." << endl;
 }
 };
 //---------------------------------------------------------------
 void processFile(graphicImage *type)
 {
 if (typeid(GIFimage) == typeid(*type))
 {
 ((GIFimage *)type)->display();
 }
 else if (typeid(PICTimage) == typeid(*type))
 {
 ((PICTimage *)type)->display();
 }
 else
 cout << "Unknown type! " << (typeid(*type)).name() << endl;
 }

 void main()
{
 graphicImage *gImage = new GIFimage();
graphicImage *pImage = new PICTimage();
gImage->display();
pImage->display();
 processFile(gImage);
 processFile(pImage);
 }
结果如下:

这个的实质是

if (typeid(GIFimage) == typeid(*type))
虽然都是phicImage指针但是类似于
graphicImage(&GIFimage)或者graphicImage(&PICTimage)这样;
 
 

该指针是在编译器中记录着,我们的代码是看不见的。

从而可以得到上述结果~


 
 

猜你喜欢

转载自blog.csdn.net/iloveyou418/article/details/52132310