资源描述:
《C中的运行时类型检查(RuntimetypecheckinC)》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库。
1、C卄中的运行时类型检查(RuntimetypecheckinC++)RuntimetypecheckinC++2009/09/2310:20,A.M.synopsisOftenpeopleask,〃howcanIdetermineorcheckthetypeofobjectinC++atruntime?"Thefollowingisademonstrationofasimpleproblem.Thefollowingprogramdisplays,zBark,zonthefirstcallofCFoo::z/AnimalSayszand〃Miaou〃onthesecondcall/z.Cl
2、assAnimal*/}{/*••;ClassDog:publicAnimal{/**/}・・;ClassCat:publicAnimalClassCFooPublic:VoidAnimalSays(Anima1*){/**/}・・・};Intmain(int,argc,char*,argv[])Dogrex;Catkitty;CFoofoo;Foo.AnimalSays(&rex);Foo.AnimalSays(&kitty);Return0;Thatis,youneedtodosomesortofmethodatruntimetodeterminethefunctionCFoo::the
3、argumentthatAnimalSaysaccepts,thepointertotheDogtypeobject,orthepointertotheCattypeobject・FirsttryOurfirstideawastoaddamembervariablethatstorestherelevantinformationaboutthetype・ttincludePublic:Enum,AnimalType,{TypeDog,TypeCat};};ClassDog:publicAnimal{Public:(Dog):m_type(TypeDog){}ConstAn
4、imalTypem_type;};ClassCat:publicAnimal{Public:(Cat):m_type(TypeCat){}};ClassCFooPublic:VoidAnimalSays(Anima1*);};Intmain(int,argc,char*,argv[]){Dogrex;Catkitty;CFoofoo;Foo.AnimalSays(&rex);Foo.AnimalSays(&kitty);Return0;VoidCFoo::AnimalSays(Animal*,pAnimal)If(((Dog*)pAnimal)->m_type二Animal::TypeDog
5、)Std::cout,,,Bark,/!z/:Elseif(((Cat*)pAnimal)->m_type二Animal::TypeCat)Std::cout,“Miaou”!〃;Now,lookingbackattheimplementationpartofCFoo::AnimalSays,imagineifwedon,thaveonlytwoanimaltypes,butmorethan50(ie,derivedclassesfromAnimal)?Asaresult,notonlyisthecodeveryugly,it'shardtomakesureit'snotwrong,it's
6、alsohardtoread,modify,andmaintain・That'snotagoodsolution.AnothergoodwaytodoitSavesclassnamesinstaticmembervariablesandaccessesthemthroughvirtualfunctions・ttincludettincludePublic:string&);string&);VirtualboolIsOfType(conststd::string&)二0;};ClassDog:publicAnimal{Staticconststringm_
7、class_name;Public:VirtualboolIsOfType(conststd::};ClassCat:publicAnimal{Staticconststringm_class_name;Public:VirtualboolIsOfType(conststd::};ClassCFooPublic:VoidAnimalSays(Anima1*);};Intmain(int,argc,char*,