我們有可能在程式執行過程中知道某個物件是屬於哪一種類別嗎?這種在 C++ 中稱為執行時期型別資訊(Runtime Type Information,RTTI)的
我們有可能在程式執行過程㆗知道某個物件是屬於哪㆒種類別嗎?這種在 C++ ㆗稱為
執行時期型別資訊(Runtime Type Information,RTTI)的能力
.
但編譯時需選用 /GR 選項(/GR 的意思是 enable C#include <typeinfo.h>
怎么找不到/GR选项呢?
可以清楚地说明一下/GR 選項在那吗?以前写完程序后,直接点击编译就可以了.
还有可以解释一下/GR 選項的功能吗?
RTTI又是怎么回事呢?
以下是一测试代码
#include <iostream.h>
#include <string.h>
class graphicImage{
protected:
char name[80];
public:
graphicImage()
{
strcpy(name,"graphicImage");
}
virtual void display()
{
cout << "Display a generic image." << endl;
}
char* getName()
{
return name;
}
};
//---------------------------------------------------------------
class GIFimage : public graphicImage
{
public:
GIFimage(){
strcpy(name,"GIFimage");
}
void display()
{
cout << "Display a GIF file." << endl;
}
};
class PICTimage : public graphicImage
{
public:
PICTimage()
{
strcpy(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();
processFile(gImage);
processFile(pImage);
}++ RTTI)