- //RTTI.CPP---built by cl -GR rtti.cpp <enter>
- #include <typeinfo.h>
- #include <iostream>
- #include <string.h>
- using namespace std;
- 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<<"Unknow type!"<<(typeid(*type)).name()<<endl;
- }
- void main()
- {
- graphicImage *gImage=new GIFimage();
- graphicImage *pImage=new PICTimage();
- processFile(gImage);
- processFile(pImage);
- }
若在DOS 下,一切正常.
若在VC6.0 IDE环境下编译,出错.
f:/rtti.cpp(57) : warning C4541: 'typeid' used on polymorphic type 'class graphicImage' with /GR-; unpredictable behavior may result
查MS
Compiler Warning (level 1) C4541
'identifier' used on polymorphic type 'type' with /GR-; unpredictable behavior may result
You did not enable run-time type information and tried to use a feature that requires run-time type information support. Recompile with the /GR switch.
For more information, see the Enable Run-Time Type Information (/GR) compiler option.
/GR (Enable Run-Time Type Information)
The Enable Run-Time Type Information option (/GR) causes the compiler to add code to check object types at run time. When this option is specified, the compiler defines the _CPPRTTI preprocessor macro. The option is cleared (/GR–) by default.
To find this option in the development environment, click Settings on the Project menu. Then click the C/C++ tab, and click C++ Language in the Category box.
For more information on run-time type checking, see Run-Time Type Information in the C++ Language Reference.