菜鸟求助,谢谢了先^_^
日期:2007-04-17 荐:
菜鸟求助,谢谢了先^_^#include<iostream> using namespace std; #include<cstdlib> #include<ctime> #include<typeinfo> class grand{ //基类 private: int hold; public: grand(int h=0):hold(h){} virtual void speak()const{cout<<" I am a grand class.";} virtual int value()const{return hold;} }; class super:public grand { public: super(int h=0):grand(h){} void speak()const{cout<<"I am a super class.";} virtual void say()const{cout<<" i hold the super value of"<<value()<<endl;} }; class mage:public super { private: char ch; public: mage(int h=0,char c='A'):super(h),ch(c){} void speak()const{cout<<"I am a mage class.";} void say()const{cout<<"I hold the characteror"<<ch<<"and the integer"<<value()<<"!";} }; grand*getone();//随机生成一个对象 int main(){ srand(time(0)); grand*pg; super*ps; for(int i=0;i<5;i ) { pg=getone(); cout<<"now processing type"<<typeid(*pg).name()<<endl; pg->speak(); if(ps=dynamic_cast<super*>(pg))ps->say(); if(typeid(mage)==typeid(*pg)) cout<<"yes you are really mage!"; } return 0; } grand*getone() { grand*p; switch(rand()%3) { case 0:p=new grand(rand()0); break; case 1:p=new super(rand()0); break; case 2:p=new mage(rand()0,'A' rand()&); break; } return p; } 编译的时候出现警告,没有错误,但不能运行,帮改改程序,谢谢了先 Compiling... 9990.cpp H:\C \练习\9990.cpp(38) : warning C4541: 'typeid' used on polymorphic type 'class grand' with /GR-; unpredictable behavior may result H:\C \练习\9990.cpp(40) : warning C4541: 'dynamic_cast' used on polymorphic type 'class grand' with /GR-; unpredictable behavior may result H:\C \练习\9990.cpp(41) : warning C4541: 'typeid' used on polymorphic type 'class grand' with /GR-; unpredictable behavior may result 在用typeid检查指针指向的派生类的时候,要在手工加入 /GR 命令。在project的setting中选择c/c ,然后在最下面的对话框中假加入 /GR 就可以了只有加入了/GR 编译器才能在运行的时候自动检查指向基类的指针现在指向哪个派生类。顺便提一下,要使用typeid判断指向哪个派生类,基类中必须要有至少一个虚函数才行,不然每次检查出来的都是指向基类工程/设置 c/c 页面 分类选择"c 语言",把"允许时间类型信息(RTTI)"勾上up搞定了, 谢谢了^_^
标签: