版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
C/C++ProgramminginterviewquestionsandanswersBySatishShetty,July14th,2004Whatisencapsulation??Containingandhidinginformationaboutanobject,suchasinternaldatastructuresandcode.Encapsulationisolates(使间隔)theinternalcomplexityofanobject'soperationfromtherestoftheapplication.Forexample,aclientcomponentaskingfornetrevenue(利润)fromabusinessobjectneednotknowthedata'sorigin.Whatisinheritance?Inheritanceallowsoneclasstoreusethestateandbehaviorofanotherclass.Thederivedclassinheritsthepropertiesandmethodimplementationsofthebaseclassandextendsitbyoverridingmethodsandaddingadditionalpropertiesandmethods.WhatisPolymorphism??Polymorphismallowsaclienttotreatdifferentobjectsinthesamewayeveniftheywerecreatedfromdifferentclassesandexhibit(显现)differentbehaviors.Youcanuseimplementation(实现)inheritancetoachievepolymorphisminlanguagessuchasC++andJava.Baseclassobject'spointercaninvoke(调用)methodsinderivedclassobjects.YoucanalsoachievepolymorphisminC++byfunctionoverloadingandoperatoroverloading.Whatisconstructororctor?Constructorcreatesanobjectandinitializesit.Italsocreatesvtable表?forvirtualfunctions.Itisdifferentfromothermethodsinaclass.
变量列Whatisdestructor?Destructorusuallydeletesanyextraresourcesallocatedbytheobject.Whatisdefaultconstructor?Constructorwithnoargumentsoralltheargumentshasdefaultvalues.Whatiscopyconstructor?Constructorwhichinitializestheit'swithanotherobjectofthesameclass.
objectmembervariables(byshallowcopying)Ifyoudon'timplementoneinyourclassthencompilerimplementsoneforyou.forexample:BooObj1(10);Membertomembercopy(shallowcopy)Whatareallthefunctions
theimplicitmemberfunctionswhichcompilerimplementsfor
oftheusif
class?wedon't
Orwhatarealldefineone.??defaultctorcopyctorassignmentoperatordefaultdestructoraddressoperatorWhatisconversionconstructor?constructorwithasingleargumentmakesthatconstructorasconversionctoranditcanbeusedfortypeconversion.forexample:classBoo{public:Boo(inti);};BooBooObject=10;forexample:classBoo{doublevalue;public:Boo(inti)operatordouble( ){returnvalue;}};BooBooObject;doublei=BooObject;nowconversionoperatorgetscalledtoassignthevalue.Whatisdiffbetweenmalloc( )/free( )andnew/delete?mallocallocatesmemoryforobjectinheapbutdoesn'tinvokeobject'sconstructortoinitiallizetheobject.newallocatesmemoryandalsoinvokesconstructortoinitializetheobject.malloc( )andfree( )donotsupportobjectsemanticsDoesnotconstructanddestructobjectsstring*ptr=(string*)(malloc(sizeof(string)))ArenotsafeDoesnotcalculatethesizeoftheobjectsthatitconstructReturnsapointertovoidint*p=(int*)(malloc(sizeof(int)));int*p=newint;Arenotextensiblenewanddeletecanbeoverloadedinaclass"delete"firstcallstheobject'sterminationroutine.itsdestructor)andthenreleasesthespacetheobjectoccupiedontheheapmemory.Ifanarrayofobjectswascreatedusingnew,thendeletemustbetoldthatitisdealingwithanarraybyprecedingthenamewithanempty[]:-Int_t*my_ints=newInt_t[10];...delete[]my_ints;whatisthediffbetween"new"and"operatornew"?"operatornew"workslikemalloc.Whatisdifferencebetweentemplateandmacro??Thereisnowayforthecompilertoverifythatthemacroparametersareofcompatibletypes.Themacroisexpandedwithoutanyspecialtypechecking.Ifmacroparameterhasapost-incrementedvariable(likec++),theincrementisperformedtwotimes.Becausemacrosareexpandedbythepreprocessor,compilererrormessageswillrefertotheexpandedmacro,ratherthanthemacrodefinitionitself.Also,themacrowillshowupinexpandedformduringdebugging.forexample:Macro:#definemin(i,j)(i<j?i:j)template:template<classT>Tmin(Ti,Tj){returni<j?i:j;}WhatareC++storageclasses?autoregisterstaticexternauto:thedefault.Variablesareautomaticallycreatedandinitializedwhentheyaredefinedandaredestroyedattheendoftheblockcontainingtheirdefinition.Theyarenotvisibleoutsidethatblockregister:atypeofautovariable.asuggestiontothecompilertouseaCPUregisterforperformancestatic:avariablethatisknownonlyinthefunctionthatcontainsitsdefinitionbutisneverdestroyedandretains=keepitsvaluebetweencallstothatfunction.Itexistsfromthetimetheprogrambeginsexecutionextern:astaticvariablewhosedefinitionandplacementisdeterminedwhenallobjectandlibrarymodulesarecombined(linked)toformtheexecutablecodefile.Itcanbevisibleoutsidethefilewhereitisdefined.WhatarestoragequalifiersinC++?Theyare..constvolatilemutableConstkeywordindicatesthatmemoryonceinitialized,shouldnotbealteredbyaprogram.volatilekeywordindicatesthatthevalueinthememorylocationcanbealteredeventhoughnothingintheprogramcodemodifiesthecontents.forexampleifyouhaveapointertohardwarelocationthatcontainsthetime,wherehardwarechangesthevalueofthispointervariableandnottheprogram.Theintentofthiskeywordtoimprovetheoptimizationabilityofthecompiler.mutablekeywordindicatesthatparticularmemberofastructureorclasscanbealteredevenifaparticularstructurevariable,class,orclassmemberfunctionisconstant.structdata{charname[80];mutabledoublesalary;}constdataMyStruct={"SatishShetty",1000};prependingvariablewith"&"symbolmakesitasreference.forexample:inta;int&b=a;&读ampWhatispassingbyreference?Methodofpassingargumentstoafunctionwhichtakesparameteroftypereference.forexample:voidswap(int&x,int&y){inttemp=x;x=y;y=temp;}inta=2,b=3;swap(a,b);Basically,insidethefunctioninsteadtheyrefertooriginalargumentsanditismoreefficient.
therewon'tbeanycopyofthearguments"x"and"y"variablesaandb.sonoextramemoryneededtopassWhendouse"const"referenceargumentsinfunction?a)Usingconstprotectsyouagainstprogrammingerrorsthatinadvertently不经意的alterdata.b)Usingconstallowsfunctiontoprocessbothconstandnon-constactualarguments,whileafunctionwithoutconstintheprototypecanonlyacceptnonconstantarguments.Usingaconstreferenceallowsthefunctiontogenerateanduseatemporaryvariableappropriately.WhenaretemporaryvariablescreatedbyC++compiler?Providedthatfunctionparameterisa"constreference",compilergeneratestemporaryvariableinfollowing2ways.Theactualargumentisthecorrecttype,butitisn'tLvaluedoubleCube(constdouble&num){num=num*num*num;returnnum;}doubletemp=;doublevalue=cube+temp);classparent{voidShow( ){cout<<"i'mparent"<<endl;}};classchild:publicparent{voidShow( ){cout<<"i'mchild"<<endl;}};parent*parent_object_ptr=newchild;parent_object_ptr->show( ).classparent{virtualvoidShow( ){cout<<"i'mparent"<<endl;}};classchild:publicparent{voidShow( ){cout<<"i'mchild"<<endl;}};parent*parent_object_ptr=newchild;parent_object_ptr->show( )Thisbaseclassiscalledabstractclassandclientwon'tabletoinstantiateanobjectusingthisbaseclass.Youcanmakeapurevirtualfunctionorabstractclassthisway..classBoo{voidfoo( )=0;}BooMyBoo;Soapointerwithtwobytealignmenthasazerointheleastsignificantbit.Andapointerwithfourbytealignmenthasazeroinboththetwoleastsignificantbits.Andsoon.Morealignmentmeansalongersequenceofzerobitsinthelowestbitsofapointer.Whatproblemdoesthenamespacefeaturesolve?Multipleprovidersoflibrariesmightusecommonglobalidentifierscausinganamecollisionwhenanapplicationtriestolinkwithtwoormoresuchlibraries.Thenamespacefeaturesurroundsalibrary'sexternaldeclarationswithauniquenamespacethateliminates除去space[identifier]{namespace-body}Anamespacedeclarationidentifiesandassignsanametoadeclarativeregion.Theidentifierinanamespacedeclarationmustbeuniqueinthedeclarativeregioninwhichitisused.Theidentifieristhenameofthenamespaceandisusedtoreferenceitsmembers.Whatistheuseof'using'declaration?Ausingdeclarationmakesitpossibletouseanamefromanamespacewithoutthescope范围operator.WhatisanIterator迭代器class?Aclassthatisusedtotraversethrough穿过theobjectsmaintainedbyacontainerclass.Therearefivecategoriesofiterators:inputiterators,outputiterators,forwarditerators,bidirectionaliterators,randomaccess.Aniteratorisanentitythatgivesaccesstothecontentsofacontainerobjectwithoutviolatingencapsulationconstraints.Accesstothecontentsisgrantedonaone-at-a-timebasisinorder.Theordercanbestorageorder(asinlistsandqueues)orsomearbitraryorder(asinarrayindices)oraccordingtosomeorderingrelation(asinanorderedbinarytree).Theiteratorisaconstruct,whichprovidesaninterfacethat,whencalled,yieldseitherthenextelementinthecontainer,orsomevaluedenotingthefactthattherearenomoreelementstoexamine.Iteratorshidethedetailsofaccesstoandupdateoftheelementsofacontainerclass.Somethinglikeapointer.Whatisadangling悬挂pointer?Adanglingpointerariseswhenyouusetheaddressofanobjectafteritslifetimeisover.Thismayoccurinsituationslikereturningaddressesoftheautomaticvariablesfromafunctionorusingtheaddressofthememoryblockafteritisfreed.WhatdoyoumeanbyStackunwinding?Itisaprocessduringexceptionhandlingwhenthedestructoriscalledforalllocalobjectsinthestackbetweentheplacewheretheexceptionwasthrownandwhereitiscaught.抛出异样与栈睁开(stackunwinding)抛出异样时,将暂停目前函数的履行,开始查找般配的catch子句。第一检查throw自己是否在try块内部,假如是,检查与该try有关的catch子句,看能否能够办理该异样。假如不可以办理,就退出目前函数,而且开释目前函数的内存并销毁局部对象,连续到上层的调用函数中查找,直到找到一个能够办理该异样的catch。这个过程称为栈睁开(stackunwinding)。当办理该异样的catch结束以后,紧接着该catch以后的点连续履行。1.为局部对象调用析构函数如上所述,在栈睁开的过程中,会开释局部对象所占用的内存并运转类种类局部对象的析构函数。但需要注意的是,假如一个块经过new动向分派内存,而且在开释该资源以前发生异样,该块因异样而退出,那么在栈睁开时期不会开释该资源,编译器不会删除该指针,这样就会造成内存泄漏。2.析构函数应当从不抛出异样在为某个异样进行栈睁开的时候,析构函数假如又抛出自己的未经办理的另一个异样,将会以致调用标准库terminate函数。平常terminate函数将调用abort函数,以致程序的非正常退出。所以析构函数应当从不抛出异样。3.异样与结构函数假如在结构函数对象时发生异样,此时该对象可能不过被部分结构,要保证能够合适的撤掉这些已结构的成员。4.未捕捉的异样将会停止程序不可以不办理异样。假如找不到般配的catch,程序就会调用库函数terminate。Nametheoperatorsthatcannotbeoverloaded??sizeof,.,.*,.->,::,?:Whatisacontainerclass?Whatarethetypesofcontainerclasses?Acontainerclassisaclassthatisusedtoholdobjectsinmemoryorexternalstorage.Acontainerclassactsasagenericholder.Acontainerclasshasapredefinedbehaviorandawell-knowninterface.Acontainerclassisasupportingclasswhosepurposeistohidethetopologyusedformaintainingthelistofobjectsinmemory.Whenacontainerclasscontainsagroupofmixedobjects,thecontaineriscalledaheterogeneous不平均的多样的container;whenthecontainerisholdingagroupofobjectsthatareallthesame,thecontaineriscalledahomogeneous单调的平均的container.Whatisinlinefunction??The__inlinekeywordtellsthecompilertosubstitute代替thecodewithinthefunctiondefinitionforeveryinstanceofafunctioncall.However,substitutionoccursonlyatthecompiler'sdiscretion灵巧性.Forexample,thecompilerdoesnotinlineafunctionifitsaddressistakenorifitistoolargetoinline.使用预办理器实现,没有了参数压栈,代码生成等一系列的操作,所以,效率很高,这是它在C中被使用的一个主要原由Whatisoverloading??WiththeC++language,youcanoverloadfunctionsandoperators.Overloadingisthepracticeofsupplyingmorethanonedefinitionforagivenfunctionnameinthesamescope.Anytwofunctionsinasetofoverloadedfunctionsmusthavedifferentargumentlists.-Overloadingfunctionswithargumentlistsofthesametypes,basedonreturntypealone,isanerror.WhatisOverriding?Tooverrideamethod,asubclassoftheclassthatoriginallydeclaredthemethodmustdeclareamethodwiththesamename,returntype(orasubclassofthatreturntype),andsameparameterlist.Thedefinitionofthemethodoverridingis:Musthavesamemethodname.Musthavesamedatatype.·Musthavesameargumentlist.Overridingamethodmeansthatreplacingamethodfunctionalityimplyoverridingfunctionalityweneedparentandchildclasses.youdefinethesamemethodsignatureasonedefinedintheparentclass.
inchildclass.ToInthechildclassWhatis"this"pointer?Thethispointerisapointeraccessibleonlywithinthememberfunctionsofaclass,struct,oruniontype.Itpointstotheobjectforwhichthememberfunctioniscalled.Staticmemberfunctionsdonothaveathispointer.Whenanon-staticmemberfunctioniscalledforanobject,theaddressoftheobjectispassedasahiddenargumenttothefunction.Forexample,thefollowingfunctioncall(3);canbeinterpreted解说thisway:setMonth(&myDate,3);Theobject'saddressisavailablefromwithinthememberfunctionasthethispointer.Itislegal,thoughunnecessary,tousethethispointerwhenreferringtomembersoftheclass.Whathappenswhenyoumakecall"deletethis;"??Thecodehastwobuilt-inpitfalls圈套/误区.First,ifitexecutesinamemberfunctionforanextern,static,orautomaticobject,theprogramwillprobablycrashassoonasthedeletestatementexecutes.Thereisnoportablewayforanobjecttotellthatitwasinstantiatedontheheap,sotheclasscannotassertthatitsobjectisproperlyinstantiated.Second,whenanobjectcommitssuicidethisway,theusingprogrammightnotknowaboutitsdemise死亡/转让.Asfarastheinstantiatingprogramisconcerned有关的,theobjectremainsinscopeandcontinuestoexisteventhoughtheobjectdiditselfin.Subsequent以后的dereferencing间接引用(dereferencingpointer重引用指针,dereferencingoperator取值运算符)ofthepointercanandusuallydoesleadtodisaster不幸.Youshouldneverdothis.Sincecompilerdoesnotknowwhethertheobjectwasallocatedonthestackorontheheap,"deletethis"couldcauseadisaster.Howvirtualfunctionsareimplemented履行C++?Virtualfunctionsareimplementedusingatableoffunctionpointers,calledthetableiscreatedbytheconstructoroftheclass.Whenaderivedclassisconstructed,itsbaseclassisconstructedfirstwhichcreatesthevtable.Ifthederivedclassoverridesanyofthebaseclassesvirtualfunctions,thoseentriesinthevtableareoverwrittenbythederivedclassconstructor.Thisiswhyyoushouldnevercallvirtualfunctionsfromaconstructor:becausethevtableentriesfortheobjectmaynothavebeensetupbythederivedclassconstructoryet,soyoumightendupcallingbaseclassimplementationsofthosevirtualfunctionsWhatisnamemanglinginC++??Theprocessofencodingtheparametertypeswiththefunction/methodnameintoauniquenameiscallednamemangling.Theinverseprocessiscalleddemangling.ForexampleFoo::bar(int,long)constismangledas`bar__C3Fooil'.Foraconstructor,themethodnameisleftout.ThatisFoo::Foo(int,long)constismangledas`__C3Fooil'.Whatisthedifferencebetweenapointerandareference?Areferencemustalwaysrefertosomeobjectand,therefore,mustalwaysbeinitialized;pointersdonothavesuchrestrictions.Apointercanbereassignedtopointtodifferentobjectswhileareferencealwaysreferstoanobjectwithwhichitwasinitialized.Howareprefixandpostfixversionsofoperator++( )differentiated?Thepostfixversionofoperator++( )hasadummyparameteroftypeint.Theprefixversiondoesnothavedummyparameter.Whatisthedifferencebetweenconstchar*myPointerandchar*constmyPointer?Constchar*myPointerisanonconstantpointertoconstantdata;whilechar*constmyPointerisaconstantpointertononconstantdata.HowcanIhandleaconstructorthatfails?throwanexception.Constructorsdon'thaveareturntype,soit'snotpossibletousereturncodes.Thebestwaytosignalconstructorfailureisthereforetothrowanexception.HowcanIhandleadestructorthatfails?Writeamessagetoalog-file.Butdonotthrowanexception.TheC++ruleisthatyoumustneverthrowanexceptionfromadestructorthatisbeingcalledduringthe"stackunwinding"processofanotherexception.Forexample,ifsomeonesaysthrowFoo( ),thestackwillbeunwoundsoallthestackframesbetweenthethrowFoo( )andthe}catch(Fooe){willgetpopped.Thisiscalledstackunwinding.Duringstackunwinding,allthelocalobjectsinallthosestackframesaredestructed.Ifoneofthosedestructorsthrowsanexception(sayitthrowsaBarobject),theC++runtimesystemisinano-winsituation:shoulditignoretheBarandendupinthe}catch(Fooe){whereitwasoriginallyheaded?ShoulditignoretheFooandlookfora}catch(Bare){handler?Thereisnogoodanswer--eitherchoicelosesinformation.SotheC++languageguaranteesthatitwillcallterminate( )atthispoint,andterminate( )killstheprocess.Bangyou'redead.WhatisVirtualDestructor?Usingvirtualdestructors,youcandestroyobjectswithoutknowingtheirtype-thecorrectdestructorfortheobjectisinvokedusingthevirtualfunctionmechanism.Notethatdestructorscanalsobedeclaredaspurevirtualfunctionsforabstractclasses.ifsomeonewillderivefromyourclass,andifsomeonewillsay"newDerived",where"Derived"isderivedfromyourclass,andifsomeonewillsaydeletep,wheretheactualobject'stypeis"Derived"butthepointerp'stypeisyourclass.Canyouthinkofasituationwhereyourprogramwouldcrashwithoutreachingthebreakpointwhichyousetatthebeginningofmain( )?C++allowsfordynamicinitializationofglobalvariablesbeforemain( )isinvoked.Itispossiblethatinitializationofglobalwillinvokesomefunction.Ifthisfunctioncrashesthecrashwilloccurbeforemain( )isentered.NametwocaseswhereyouMUSTuseinitializationlistasopposedtoassignmentinconstructors.Bothnon-staticconstdatamembersandreferencedatamemberscannotbeassignedvalues;instead,youshoulduseinitializationlisttoinitializethem.Canyouoverloadafunctionbasedonlyonwhetheraparameterisavalueorareference?No.Passingbyvalueandbyreferencelooksidenticaltothecaller.WhatarethedifferencesbetweenaC++structandC++class?Thedefaultmemberandbaseclassaccessspecifiers表记符aredifferent.TheC++structhasallthefeaturesoftheclass.Theonlydifferencesarethatastructdefaultstopublicmemberaccessandpublicbaseclassinheritance,andaclassdefaultstotheprivateaccessspecifierandprivatebaseclassinheritance.Whatdoesextern"C"intfunc(int*,Foo)accomplish实现/达到/达成?Itwillturnoff"namemangling"forfuncsothatonecanlinktocodecompiledbyaCcompiler.Howdoyouaccessthestaticmemberofaclass?<ClassName>::<StaticMemberName>Whatismultipleinheritance(virtualinheritance)?Whatareitsadvantagesanddisadvantages?MultipleInheritanceistheprocesswhereby经过achildcanbederivedfrommorethanoneparentclass.Theadvantageofmultipleinheritanceisthatitallowsaclasst
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2024年出售旧砖楼板合同范本
- 2024年出口风扇采购合同范本
- 受伤人员的紧急救护培训
- 古诗文默写集合
- 2023-2024学年广州七年级语文上学期开学摸底考试卷(含答案)
- 《页岩气的研究报告》课件
- 【高中数学课件】抽样方法(复习课)
- 2024蔬菜种子买卖合同
- 2024建造船舶合同范文
- 2024至2030年中国插座总成行业投资前景及策略咨询研究报告
- 人音版初中音乐 九年级上册 中考一轮复习课件
- 施工机器人应用方案
- 肝硬化食管胃底静脉曲张破裂出血的诊治
- 概率论(华南农业大学)智慧树知到课后章节答案2023年下华南农业大学
- 大学生幸福感调查报告-2
- 一日生活中幼儿自主探究行为的表现及支持策略研究
- 第8课 用制度体系保证人民当家做主
- 我们的出行方式 (教学设计)2022-2023学年综合实践活动四年级上册 全国通用
- 物品放行操作规程及放行条样板
- 新苏教版六年级上册科学全册知识点(精编)
- 2023新能源光伏发电项目索结构柔性光伏支架施工方案
评论
0/150
提交评论