版權說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權,請進行舉報或認領
文檔簡介
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(調用)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有關的catch子句,看能否能夠辦理該異樣。假如不可以辦理,就退出目前函數(shù),而且開釋目前函數(shù)的內(nèi)存并銷毀局部對象,連續(xù)到上層的調用函數(shù)中查找,直到找到一個能夠辦理該異樣的catch。這個過程稱為棧睜開(stackunwinding)。當辦理該異樣的catch結束以后,緊接著該catch以后的點連續(xù)履行。1.為局部對象調用析構函數(shù)如上所述,在棧睜開的過程中,會開釋局部對象所占用的內(nèi)存并運轉類種類局部對象的析構函數(shù)。但需要注意的是,假如一個塊經(jīng)過new動向分派內(nèi)存,而且在開釋該資源以前發(fā)生異樣,該塊因異樣而退出,那么在棧睜開時期不會開釋該資源,編譯器不會刪除該指針,這樣就會造成內(nèi)存泄漏。2.析構函數(shù)應當從不拋出異樣在為某個異樣進行棧睜開的時候,析構函數(shù)假如又拋出自己的未經(jīng)辦理的另一個異樣,將會以致調用標準庫terminate函數(shù)。平常terminate函數(shù)將調用abort函數(shù),以致程序的非正常退出。所以析構函數(shù)應當從不拋出異樣。3.異樣與結構函數(shù)假如在結構函數(shù)對象時發(fā)生異樣,此時該對象可能不過被部分結構,要保證能夠合適的撤掉這些已結構的成員。4.未捕捉的異樣將會停止程序不可以不辦理異樣。假如找不到般配的catch,程序就會調用庫函數(shù)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.使用預辦理器實現(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死亡/轉讓.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實現(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)系上傳者。文件的所有權益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
- 4. 未經(jīng)權益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
- 6. 下載文件中如有侵權或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 孕期手指發(fā)麻的健康宣教
- 《預算培訓材料》課件
- 紅痣的臨床護理
- 《機械設計基礎 》課件-第1章
- 李寧公司導購銷售技巧培訓課件
- 化學反應的方向課件
- 動量定理的應用課件
- JJF(陜) 104-2023 裂隙燈顯微鏡校準規(guī)范
- JJF(陜) 016-2019 呼吸器綜合檢測儀校準規(guī)范
- 《酒店對客服務培訓》課件
- 戰(zhàn)爭與謀略:第二次世界大戰(zhàn)經(jīng)典戰(zhàn)役評析知到智慧樹章節(jié)測試課后答案2024年秋西安交通大學
- 2023年益陽市安化縣招聘鄉(xiāng)鎮(zhèn)衛(wèi)生院護理人員考試真題
- 2025年九年級中考數(shù)學專題復習-二次函數(shù)綜合壓軸題(與最值有關的問題)(含簡單答案)
- 中國多發(fā)性骨髓瘤診治指南(2024年修訂)解讀
- 廣西南寧市2023-2024學年高二上學期期末考試+歷史 含解析
- 2024年醫(yī)院醫(yī)保工作總結(6篇)
- 南京信息工程大學《數(shù)學分析1》2021-2022學年第一學期期末試卷
- 咨詢咨詢合同三篇
- 時尚與品牌學習通超星期末考試答案章節(jié)答案2024年
- 人教版三年級上冊數(shù)學期末試卷含答案
- 西峽課件完整版本
評論
0/150
提交評論