C常見英文面試筆試題_第1頁
C常見英文面試筆試題_第2頁
C常見英文面試筆試題_第3頁
C常見英文面試筆試題_第4頁
C常見英文面試筆試題_第5頁
已閱讀5頁,還剩9頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)

文檔簡介

C/C++ProgramminginterviewquestionsandanswersBySatishShetty,July14th,2004Whatisencapsulation??Containingandhidinginformationaboutanobject,suchasinternaldatastructuresandcode.Encapsulationisolates(使間隔)theinternalcomplexityofanobject'soperationfromtherestoftheapplication.Forexample,aclientcomponentaskingfornetrevenue(利潤)fromabusinessobjectneednotknowthedata'sorigin.Whatisinheritance?Inheritanceallowsoneclasstoreusethestateandbehaviorofanotherclass.Thederivedclassinheritsthepropertiesandmethodimplementationsofthebaseclassandextendsitbyoverridingmethodsandaddingadditionalpropertiesandmethods.WhatisPolymorphism??Polymorphismallowsaclienttotreatdifferentobjectsinthesamewayeveniftheywerecreatedfromdifferentclassesandexhibit(顯現(xiàn))differentbehaviors.Youcanuseimplementation(實現(xiàn))inheritancetoachievepolymorphisminlanguagessuchasC++andJava.Baseclassobject'spointercaninvoke(調(diào)用)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不經(jīng)意的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)拋出異樣時,將暫停目前函數(shù)的履行,開始查找般配的catch子句。第一檢查throw自己是否在try塊內(nèi)部,假如是,檢查與該try有關(guān)的catch子句,看能否能夠辦理該異樣。假如不可以辦理,就退出目前函數(shù),而且開釋目前函數(shù)的內(nèi)存并銷毀局部對象,連續(xù)到上層的調(diào)用函數(shù)中查找,直到找到一個能夠辦理該異樣的catch。這個過程稱為棧睜開(stackunwinding)。當辦理該異樣的catch結(jié)束以后,緊接著該catch以后的點連續(xù)履行。1.為局部對象調(diào)用析構(gòu)函數(shù)如上所述,在棧睜開的過程中,會開釋局部對象所占用的內(nèi)存并運轉(zhuǎn)類種類局部對象的析構(gòu)函數(shù)。但需要注意的是,假如一個塊經(jīng)過new動向分派內(nèi)存,而且在開釋該資源以前發(fā)生異樣,該塊因異樣而退出,那么在棧睜開時期不會開釋該資源,編譯器不會刪除該指針,這樣就會造成內(nèi)存泄漏。2.析構(gòu)函數(shù)應當從不拋出異樣在為某個異樣進行棧睜開的時候,析構(gòu)函數(shù)假如又拋出自己的未經(jīng)辦理的另一個異樣,將會以致調(diào)用標準庫terminate函數(shù)。平常terminate函數(shù)將調(diào)用abort函數(shù),以致程序的非正常退出。所以析構(gòu)函數(shù)應當從不拋出異樣。3.異樣與結(jié)構(gòu)函數(shù)假如在結(jié)構(gòu)函數(shù)對象時發(fā)生異樣,此時該對象可能不過被部分結(jié)構(gòu),要保證能夠合適的撤掉這些已結(jié)構(gòu)的成員。4.未捕捉的異樣將會停止程序不可以不辦理異樣。假如找不到般配的catch,程序就會調(diào)用庫函數(shù)terminate。Nametheoperatorsthatcannotbeoverloaded??sizeof,.,.*,.->,::,?:Whatisacontainerclass?Whatarethetypesofcontainerclasses?Acontainerclassisaclassthatisusedtoholdobjectsinmemoryorexternalstorage.Acontainerclassactsasagenericholder.Acontainerclasshasapredefinedbehaviorandawell-knowninterface.Acontainerclassisasupportingclasswhosepurposeistohidethetopologyusedformaintainingthelistofobjectsinmemory.Whenacontainerclasscontainsagroupofmixedobjects,thecontaineriscalledaheterogeneous不平均的多樣的container;whenthecontainerisholdingagroupofobjectsthatareallthesame,thecontaineriscalledahomogeneous單調(diào)的平均的container.Whatisinlinefunction??The__inlinekeywordtellsthecompilertosubstitute代替thecodewithinthefunctiondefinitionforeveryinstanceofafunctioncall.However,substitutionoccursonlyatthecompiler'sdiscretion靈巧性.Forexample,thecompilerdoesnotinlineafunctionifitsaddressistakenorifitistoolargetoinline.使用預辦理器實現(xiàn),沒有了參數(shù)壓棧,代碼生成等一系列的操作,所以,效率很高,這是它在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圈套/誤區(qū).First,ifitexecutesinamemberfunctionforanextern,static,orautomaticobject,theprogramwillprobablycrashassoonasthedeletestatementexecutes.Thereisnoportablewayforanobjecttotellthatitwasinstantiatedontheheap,sotheclasscannotassertthatitsobjectisproperlyinstantiated.Second,whenanobjectcommitssuicidethisway,theusingprogrammightnotknowaboutitsdemise死亡/轉(zhuǎn)讓.Asfarastheinstantiatingprogramisconcerned有關(guān)的,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實現(xiàn)/達到/達成?Itwillturnoff"namemangling"forfuncsothatonecanlinktocodecompiledbyaCcompiler.Howdoyouaccessthestaticmemberofaclass?<ClassName>::<StaticMemberName>Whatismultipleinheritance(virtualinheritance)?Whatareitsadvantagesanddisadvantages?MultipleInheritanceistheprocesswhereby經(jīng)過achildcanbederivedfrommorethanoneparentclass.Theadvantageofmultipleinheritanceisthatitallowsaclasst

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
  • 6. 下載文件中如有侵權(quán)或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論