2023年C++常见英文面试笔试题_第1页
2023年C++常见英文面试笔试题_第2页
2023年C++常见英文面试笔试题_第3页
2023年C++常见英文面试笔试题_第4页
2023年C++常见英文面试笔试题_第5页
已阅读5页,还剩19页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

C/C++ProgramminginterviewquestionsandanswersBySatishShetty,July14th,Whatisencapsulation??

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'sobjectmembervariables(byshallowcopying)withanotherobjectofthesameclass.Ifyoudon'timplementoneinyourclassthencompilerimplementsoneforyou.forexample:

BooObj1(10);//callingBooconstructorBooObj2(Obj1);//callingboocopyconstructor

BooObj2=Obj1;//callingboocopyconstructorWhenarecopyconstructorscalled?Copyconstructorsarecalledinfollowingcases:

a)whenafunctionreturnsanobjectofthatclassbyvalue

b)whentheobjectofthatclassispassedbyvalueasanargumenttoafunction

c)whenyouconstructanobjectbasedonanotherobjectofthesameclass

d)Whencompilergeneratesatemporaryobject

Whatisassignmentoperator?Defaultassignmentoperatorhandlesassigningoneobjecttoanotherofthesameclass.Membertomembercopy(shallowcopy)

Whatarealltheimplicitmemberfunctionsoftheclass?Orwhatareallthefunctionswhichcompilerimplementsforusifwedon'tdefineone.??defaultctor

copyctor

assignmentoperator

defaultdestructor

addressoperator

Whatisconversionconstructor?constructorwithasingleargumentmakesthatconstructorasconversionctoranditcanbeusedfortypeconversion.forexample:classBoo

{

public:

Boo(inti);

};

BooBooObject=10;//assigningint10Booobject

Whatisconversionoperator??

classcanhaveapublicmethodforspecificdatatypeconversions.forexample:

classBoo

{

doublevalue;

public:

Boo(inti)

operatordouble()

{

returnvalue;

}

};

BooBooObject;

doublei=BooObject;//assigningobjecttovariableioftypedouble.nowconversionoperatorgetscalledtoassignthevalue.

Whatisdiffbetweenmalloc()/free()andnew/delete?mallocallocatesmemoryforobjectinheapbutdoesn'tinvokeobject'sconstructortoinitiallizetheobject.newallocatesmemoryandalsoinvokesconstructortoinitializetheobject.malloc()andfree()donotsupportobjectsemantics

Doesnotconstructanddestructobjects

string*ptr=(string*)(malloc(sizeof(string)))

Arenotsafe

Doesnotcalculatethesizeoftheobjectsthatitconstruct

Returnsapointertovoid

int*p=(int*)(malloc(sizeof(int)));

int*p=newint;

Arenotextensible

newanddeletecanbeoverloadedinaclass"delete"firstcallstheobject'sterminationroutine(i.e.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?auto

register

static

externauto:thedefault.Variablesareautomaticallycreatedandinitializedwhentheyaredefinedandaredestroyedattheendoftheblockcontainingtheirdefinition.Theyarenotvisibleoutsidethatblockregister:atypeofautovariable.asuggestiontothecompilertouseaCPUregisterforperformancestatic:avariablethatisknownonlyinthefunctionthatcontainsitsdefinitionbutisneverdestroyedandretains=keepitsvaluebetweencallstothatfunction.Itexistsfromthetimetheprogrambeginsexecutionextern:astaticvariablewhosedefinitionandplacementisdeterminedwhenallobjectandlibrarymodulesarecombined(linked)toformtheexecutablecodefile.Itcanbevisibleoutsidethefilewhereitisdefined.

WhatarestoragequalifiersinC++?Theyare..const

volatile

mutableConstkeywordindicatesthatmemoryonceinitialized,shouldnotbealteredbyaprogram.volatilekeywordindicatesthatthevalueinthememorylocationcanbealteredeventhoughnothingintheprogram

codemodifiesthecontents.forexampleifyouhaveapointertohardwarelocationthatcontainsthetime,wherehardwarechangesthevalueofthispointervariableandnottheprogram.Theintentofthiskeywordtoimprovetheoptimizationabilityofthecompiler.mutablekeywordindicatesthatparticularmemberofastructureorclasscanbealteredevenifaparticularstructurevariable,class,orclassmemberfunctionisconstant.structdata

{

charname[80];

mutabledoublesalary;

}constdataMyStruct={"SatishShetty",1000};//initlizedbycomplierstrcpy(MyS,"ShilpaShetty");//compilererror

MyStruct.salaray=;//complierishappyallowed

Whatisreference??referenceisanamethatactsasanalias,oralternativename,forapreviouslydefinedvariableoranobject.prependingvariablewith"&"symbolmakesitasreference.forexample:inta;

int&b=a;&读amp

Whatispassingbyreference?Methodofpassingargumentstoafunctionwhichtakesparameteroftypereference.forexample:voidswap(int&x,int&y)

{

inttemp=x;

x=y;

y=temp;

}inta=2,b=3;swap(a,b);

Basically,insidethefunctiontherewon'tbeanycopyofthearguments"x"and"y"insteadtheyrefertooriginalvariablesaandb.sonoextramemoryneededtopassargumentsanditismoreefficient.

Whendouse"const"referenceargumentsinfunction?a)Usingconstprotectsyouagainstprogrammingerrorsthatinadvertently不经意旳alterdata.

b)Usingconstallowsfunctiontoprocessbothconstandnon-constactualarguments,whileafunctionwithoutconstintheprototypecanonlyacceptnonconstantarguments.

c)Usingaconstreferenceallowsthefunctiontogenerateanduseatemporaryvariableappropriately.

WhenaretemporaryvariablescreatedbyC++compiler?Providedthatfunctionparameterisa"constreference",compilergeneratestemporaryvariableinfollowing2ways.a)Theactualargumentisthecorrecttype,butitisn'tLvaluedoubleCube(constdouble&num)

{

num=num*num*num;

returnnum;}doubletemp=2.0;

doublevalue=cube(3.0+temp);//argumentisaexpressionandnotaLvalue;

b)Theactualargumentisofthewrongtype,butofatypethatcanbeconvertedtothecorrecttypelongtemp=3L;

doublevalue=cuberoot(temp);//longtodoubleconversion

Whatisvirtualfunction?

Whenderivedclassoverridesthebaseclassmethodbyredefiningthesamefunction,thenifclientwantstoaccessredefinedthemethodfromderivedclassthroughapointerfrombaseclassobject,thenyoumustdefinethisfunctioninbaseclassasvirtualfunction.classparent

{

voidShow()

{

cout<<"i'mparent"<<endl;

}

};

classchild:publicparent

{

voidShow()

{

cout<<"i'mchild"<<endl;

}};

parent*parent_object_ptr=newchild;parent_object_ptr->show()//callsparent->show()i

nowwegotovirtualworld...classparent

{

virtualvoidShow()

{

cout<<"i'mparent"<<endl;

}

};

classchild:publicparent

{

voidShow()

{

cout<<"i'mchild"<<endl;

}};

parent*parent_object_ptr=newchild;parent_object_ptr->show()//callschild->show()

Whatispurevirtualfunction?orwhatisabstractclass?

Whenyoudefineonlyfunctionprototypeinabaseclasswithoutimplementationanddothecompleteimplementation实现inderivedclass.Thisbaseclassiscalledabstractclassandclientwon'tabletoinstantiateanobjectusingthisbaseclass.Youcanmakeapurevirtualfunctionorabstractclassthisway..classBoo

{

voidfoo()=0;

}

BooMyBoo;//compilationerror

WhatisMemoryalignment??Thetermalignmentprimarilymeansthetendency趋向ofanaddresspointervaluetobeamultipleofsomepoweroftwo.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.

Overridingamethodmeansthatreplacingamethodfunctionalityinchildclass.Toimplyoverridingfunctionalityweneedparentandchildclasses.Inthechildclassyoudefinethesamemethodsignatureasonedefinedintheparentclass.

Whatis"this"pointer?Thethispointerisapointeraccessibleonlywithinthememberfunctionsofaclass,struct,oruniontype.Itpointstotheobjectforwhichthememberfunctioniscalled.Staticmemberfunctionsdonothaveathispointer.Whenanon-staticmemberfunctioniscalledforanobject,theaddressoftheobjectispassedasahiddenargumenttothefunction.Forexample,thefollowingfunctioncallmyDate.setMonth(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,calledthevtable.Thereisoneentryinthetablepervirtualfunctionintheclass.Thistableiscreatedbytheconstructoroftheclass.Whenaderivedclassisconstructed,itsbaseclassisconstructedfirstwhichcreatesthevtable.Ifthederivedclassoverridesanyofthebaseclassesvirtualfunctions,thoseentriesinthevtableareoverwrittenbythederivedclassconstructor.Thisiswhyyoushouldnevercallvirtualfunctionsfromaconstructor:becausethevtableentriesfortheobjectmaynothavebeensetupbythederivedclassconstructoryet,soyoumightendupcallingbaseclassimplementationsofthosevirtualfunctions

WhatisnamemanglinginC++??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.Theadvantageofmultipleinheritanceisthatitallowsaclasstoinheritthefunctionality功能ofmorethanonebaseclassthus因此allowingformodeling建模ofcomplexrelati

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论