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

下載本文檔

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

文檔簡介

1、C/C+ Programmi ng in terview questi ons and an swersBy Satish Shetty, July 14th, 2004What is en capsulatio n?Con tai ning and hidi ng in formatio n about an object, such as in ternaldata structuresand code. En capsulati on isolates( 使隔離)the in ternal complexity of an objects operation from the rest

2、of the application. For example, a client component asking for net reve nue(收益)from a bus in ess object n eed not know the datas origi n.What is in herita nee?Inheritanee allows one class to reuse the state and behavior of another class. The derived class inherits the properties and method implement

3、ations of the base class and extends it by overridingmethods and adding additionalproperties and methods.What is Polymorphism?Polymorphism allows a clie nt to treat differe nt objects in the same way eve n ifthey were created from different classes and exhibit(展現(xiàn)) differentbehaviors.You can use impl

4、ementation (實現(xiàn))inheritaneeto achieve polymorphism in Ianguagessuch as C+ and Java.Base class objects poin ter can inv oke(調(diào)用) methods in derived class objects.You can also achieve polymorphism in C+ by function overloadi ng and operator overload ing.What is con structor or ctor?Con structor creates

5、an object and in itializes it. It also creates vtable變量歹 U表? for virtual functions. It is different from other methods in a class.What is destructor?Destructor usually deletes any extra resources allocated by the object.What is default con structor?Con structor with no argume nts or all the argume n

6、ts has default values.What is copy con structor?Constructor which initializes the its object membervariables ( by shallow copying) with ano ther object of the same class. If you dont impleme nt one in your class the n compiler impleme nts one for you.for example:Boo Obj1(10); / calli ng Boo con stru

7、ctorBoo Obj2(Obj1); / calli ng boo copy con structorBoo Obj2 = Obj1; call ing boo copy con structorWhen are copy con structors called?Copy con structors are called in follow ing cases:whe n a function retur ns an object of that class by valuewhe n the object of that class is passed by value as an ar

8、gume nt to a fun cti onwhe n you con struct an object based on ano ther object of the same classWhen compiler gen erates a temporary objectWhat is assig nment operator?Default assig nment operator han dles assig ning one object to ano ther of the same class. Member to member copy (shallow copy)What

9、are all the implicit member functions of the class? Or what are all the functions which compiler impleme nts for us if we dont defi ne on e.?default ctorcopy ctorassig nment operatordefault destructoraddress operatorWhat is con versi on con structor?con structor with a si ngle argume nt makes that c

10、on structor as conv ersi on ctor and it can be used for type conv ersi on.for example:class Boopublic:Boo( int i );Boo BooObject = 10 ; / assig ning int 10 Boo objectWhat is con versi on operator?class can have a public method for specific data type con versi ons.for example:class Boodouble value;pu

11、blic:Boo(i nt i )operator double()return value;Boo BooObject;double i = BooObject; / assig ning object to variable i of type double. nowcon versi on operator gets called to assig n the value.con structorWhat is diff betwee n malloc()/free() and n ew/delete?malloc allocates memoryfor object in heap b

12、ut does nt inv oke objects to in itiallize the object.new allocates memory and also inv okes con structor to in itialize the object.malloc() and free() do not support object sema nticsDoes not con struct and destruct objectsstri ng * ptr = (stri ng *)(malloc (sizeof(stri ng)Are not safeDoes not calc

13、ulate the size of the objects that it con structRetur ns a poin ter to voidint *p = (int *) (malloc(sizeof(i nt);int *p = new int;Are not exte nsiblenew and delete can be overloaded in a classdelete first calls the objects term in ati on routi ne (i.e. its destructor) andthe n releases the space the

14、 object occupied on the heap memory. If an array of objects was created using n ew, the n delete must be told that it is deali ng with an array by precedi ng the n ame with an empty :-Int_t *my_i nts = new In t_t10;delete my_i nts;what is the diff betwee n n ew and operator n ew ?operator n ew works

15、 like malloc.What is differe nee betwee n template and macro?There is no way for the compiler to verify that the macro parameters are of compatible types. The macro is expa nded without any special type check ing.referIf macro parameter has a post-i ncreme nted variable ( like c+ ), the in creme nt

16、is performed two times.Because macros are expanded by the preprocessor, compiler error messageswill to the expa nded macro, rather tha n the macro defi niti on itself. Also, the macro will show up in expa nded form duri ng debugg ing.for example:Macro:#defi ne min (i, j) (i j ? i : j)template:templa

17、teT min (T i, T j)retur n i j ? i : j;What are C+ storage classes?autoregisterstaticexter nauto: the default. Variables are automatically created and initialized when theyare defined and are destroyed at the end of the block containing their definition.They are not visible outside that blockregister

18、:a type of auto variable. a suggestion to the compiler to use a CPUregisterfor performa neestatic:a variable that is known only in the function that contains its definition but is n ever destroyed and reta in s=keep its value betwee n calls to that fun cti on.It exists from the time the program beg

19、ins executi onexter n: a static variable whose defi niti on and placeme nt is determ ined whe n allobject and library modules are combined (linked) to form the executable code file.It can be visible outside the file where it is defi ned.What are storage qualifiers in C+ ?They are.con stvolatilemutab

20、leCon st keyword in dicates that memory once in itialized, should not be altered by aprogram.volatilekeyword indicates that the value in the memorylocation can be altered eventhough no thi ng in the programcode modifies the contents. for example if you have a pointer to hardware location that contai

21、ns the time, where hardware cha nges the value of this poin ter variableand not the program. The intent of this keyword to improve the optimization ability of the compiler.mutable keyword in dicates that particular member of a structure or class can be altered eve n if a particular structure variabl

22、e, class, or class member fun ctio n is con sta nt.struct datachar n ame80;mutable double salary;const data MyStruct = Satish Shetty, 1000 ; /in itlized by complierstrcpy ( MyStruct. name, Shilpa Shetty); / compiler errorMyStruct.salaray = 2000 ; / complier is happy allowedWhat is refere nee ?refere

23、 nee is a n ame that acts as an alias, or alter native n ame, for a previously defi ned variable or an object.prepe nding variable with & symbol makes it as refere nee. for example:int a;int &b = a;& 讀 ampWhat is pass ing by refere nee?Method of passing arguments to a function which takes parameter

24、of type referenee. for example:void swap( int & x, int & y )int temp = x;x = y;y = temp;int a=2, b=3;swap( a, b );Basically, in side the fun cti on there wont be any copy of the argume nts x and y i nstead they refer to origi nal variables a and b. so no extra memory n eeded to pass argume nts and i

25、t is more efficie nt.When do use con st refere nee argume nts in function?不經(jīng)argume nts.Using const protects you aga inst program ming errors that in adverte ntly 意的 alter data.Using const allows function to process both const and non-const actual while a function without const in the prototype can o

26、nly accept non con sta nt argume nts.Using a const refere nee allows the fun cti on to gen erate and use a temporary variable appropriately.gen eratesWhe n are temporary variables created by C+ compiler?Provided that functionparameter is a const referenee, compilertemporary variable in followi ng 2

27、ways.The actual argume nt is the correct type, but it isnt Lvaluedouble Cube(c onst double & num)num = num * num * num;return num;double temp = 2.0;double value = cube(3.0 + temp); / argume nt is a expressi on and n ot a Lvalue;The actual argume nt is of the wrong type, but of a type that can be con

28、 verted to the correct typelong temp = 3L;double value = cuberoot ( temp); /long to double conv ersi onWhat is virtual function?Whenderived class overrides the base class method by redefining the samefunction, the n if clie nt wants to access redefi ned the method from derived class through a poin t

29、er from base class object, the n you must defi ne this fun cti on in base class as virtual function.class pare ntvoid Show()cout im pare nt en dl;class child: public pare ntvoid Show()cout im child show() / calls pare nt-show() inow we goto virtual world.class pare ntvirtual void Show()cout im pare

30、nt en dl;;class child: public pare ntvoid Show()cout im child show() / calls child-show()What is pure virtual fun cti on? or what is abstract class?Whenyou define only functionprototype in a base class without implementation anddo the complete impleme ntati on實現(xiàn) in derived class. This base class is

31、calledabstract class and client wont able to instantiatean object using this base class.You can make a pure virtual fun cti on or abstract class this way.class Boovoid foo() = 0;Boo MyBoo; / compilati on errorWhat is Memory alig nmen t?The term alignment primarily means the tendency 趨向 of an address

32、 pointer value to be a multiple of some power of two. So a poin ter with two byte alig nment has a zero in the least sig ni fica nt bit. And a poin ter with four byte alig nment has a zero in both the two least sig nifica nt bits. And so on. More alig nment means aIon ger seque nee of zero bits in t

33、he lowest bits of a poin ter.What problem does the n amespace feature solve?Multiple providers of libraries might use commonglobal identifierscausing a namecollisio n whe n an applicati on tries to link with two or more such libraries. Thenamespace featuresurrounds a librarysexternaldeclarationswith

34、 a uniquen amespace that elimi nates了肖除 the pote ntial for those collisi ons.n amespace ide ntifier n amespace-body A n amespace declarati on ide ntifies and assig ns a n ame to a declarative regi on.The identifier in a namespacedeclarationmust be unique in the declarativeregionin which it is used.

35、The ide ntifier is the n ame of the n amespace and is used to refere nee its members.What is the use of us ing declarati on?A using declarati on makes it possible to use a n ame from a n amespace without the scope 范圍 operator.What is an Iterator 迭代器 class?A class that is used to traverse through 穿過

36、the objects maintained by a container class. There are five categories of iterators:in put iterators, output iterators,forward iterators,bidirectionaliterators, randomaccess. An iterator is an entitythat gives access to the contents of a container object withoutviolatingen capsulati on con strai nts

37、. Access to the contents is gran ted on a on e-at-a-time basis in order. The order can be storage order (as in lists and queues) or some arbitrary order (as in array in dices) or accord ing to some orderi ng relati on (asin an ordered binary tree). The iterator is a con struct,which provides an in t

38、erfacethat, whe n called, yields either the n ext eleme nt in the container, or some value denoting the fact that there are no more eleme nts to exam in e. Iterators hide the details of access to and update of the eleme nts of a container class. Someth ing like a poin ter.What is a dan gli ng 懸掛 poi

39、n ter?A dangling pointer arises when you use the address of an object after its lifetime is over. This may occur in situati ons like returni ng addresses of the automaticvariables from a function or using the address of the memoryblock after it is freed.What do you mean by Stack unwinding?It is a pr

40、ocess duri ng excepti on han dli ng when the destructor is called for alllocal objects in the stack betwee n the place where the exceptio n was throw n and where it is caught.拋出異常與棧展開(stack unwinding )拋出異常時,將暫停當(dāng)前函數(shù)的執(zhí)行,開始查找匹配的catch子句。首先檢查throw本身是否在try塊內(nèi)部,如果是,檢查與該try相關(guān)的catch子句,看是否可以處理該異常。 如果不能處理,就退出當(dāng)前

41、函數(shù),并且釋放當(dāng)前函數(shù)的內(nèi)存并銷毀局部對象,繼續(xù)到上層 的調(diào)用函數(shù)中查找,直到找到一個可以處理該異常的catch。這個過程稱為棧展開(stackunwinding )。當(dāng)處理該異常的catch結(jié)束之后,緊接著該catch之后的點繼續(xù)執(zhí)行。為局部對象調(diào)用析構(gòu)函數(shù)如上所述,在棧展開的過程中,會釋放局部對象所占用的內(nèi)存并運行類類型局部對象的析 構(gòu)函數(shù)。但需要注意的是,如果一個塊通過new動態(tài)分配內(nèi)存,并且在釋放該資源之前發(fā)生異常,該塊因異常而退出,那么在棧展開期間不會釋放該資源,編譯器不會刪除該指針, 這樣就會造成內(nèi)存泄露。析構(gòu)函數(shù)應(yīng)該從不拋出異常在為某個異常進(jìn)行棧展開的時候,析構(gòu)函數(shù)如果又拋出自己

42、的未經(jīng)處理的另一個異常,將 會導(dǎo)致調(diào)用標(biāo)準(zhǔn)庫terminate函數(shù)。通常terminate函數(shù)將調(diào)用abort函數(shù),導(dǎo)致程序的 非正常退出。所以析構(gòu)函數(shù)應(yīng)該從不拋出異常。異常與構(gòu)造函數(shù)如果在構(gòu)造函數(shù)對象時發(fā)生異常,此時該對象可能只是被部分構(gòu)造,要保證能夠適當(dāng)?shù)某?銷這些已構(gòu)造的成員。未捕獲的異常將會終止程序不能不處理異常。如果找不到匹配的catch,程序就會調(diào)用庫函數(shù)terminate 。Name the operators that cannot be overloaded?sizeof, ., .*, .-, :, ?:What is a container class? What are

43、 the types of container classes?A container class is a class that is used to hold objects in memory or exter nalstorage. A container class acts as a gen eric holder. A container class has apredefi ned behavior and a well-k nown in terface. A container class is a support ingclass whose purpose is to

44、hide the topology used for maintaining the list of objects in memory. Whena container class contains a group of mixed objects, the container is called a heterogeneous 不均勻的多樣的 container; when the container is holdinga group of objects that are all the same, the container is called a homogeneous 單一的均勻

45、的container.標(biāo)準(zhǔn)容器類特點順序性容器vector從后面快速的拉入與刪除,直接訪問任何元素deque從前面或后面快速的插入與刪除.直接訪問任何元索list雙鏈表,從任何地方快速插入與刪除關(guān)聯(lián)容器set快速杳找.不允許重復(fù)值multiset快速查找,允許重復(fù)他map一對多映愆基丁咲鍵手快速杳找,不允許重復(fù)倩multimap一對多映射,甚于關(guān)鍵字快速查找,允許重夏值容器適配器stack后進(jìn)先出queue先進(jìn)先出priority_queue最高優(yōu)先級元素總是第一個出列What is inline fun ctio n?The _in li ne keyword tells the compi

46、ler to substitute替代 the code within thefunction defi niti on for every in sta nee of a function call. However, substituti on occurs only at the compilers discretion靈活性.For example, the compiler doesnot inline a function if its address is taken or if it is too large to inline.使用預(yù)處理器實現(xiàn),沒有了參數(shù)壓棧,代碼生成等一系

47、列的操作,因此,效率很高,這 是它在C中被使用的一個主要原因What is overloadi ng?With the C+ Ian guage, you can overload functions and operators. Overload ing isthe practice of suppl ying more tha n one defi niti on for a give n function n ame inthe same scope.-Any two fun cti ons in a set of overloaded fun cti ons must have dif

48、fere nt argume ntlists.-Overloading functions with argument lists of the sametypes, based on return type alon e, is an error.What is Overridi ng?To override a method, a subclass of the class that orig in ally declared the methodmust declare a method with the same name, return type (or a subclass of

49、that return type), and same parameter list.The defi niti on of the method overrid ing is:Must have same method n ame.Must have same data type.Must have same argume nt list.Overrid ing a method means that replac ing a method fun ctio nality in child class.To imply overrid ing fun ctio nality we n eed

50、 pare nt and child classes. In the child class you defi ne the same method sig nature as one defi ned in the pare nt class.What is this poi nter?The this pointer is a pointer accessible only within the memberfunctions of a class, struct, or union type. It points to the object for which the member fu

51、n ctio n iscalled. Static member functions do not have a this poin ter.Whena non-static memberfunction is called for an object, the address of the object is passed as a hidden argument to the function. For example, the following function callmyDate.setM on th( 3 );can be in terpreted 解釋 this way:set

52、Mo nth( &m yDate, 3 );The objects address is available from within the member fun cti on as the thispoin ter. It is legal, though unn ecessary, to use the this poin ter whe n referri ngto members of the class.What happe ns whe n you make call delete this; ?The code has two built-in pitfalls陷阱/ 誤區(qū).Fi

53、rst, if it executes in a memberfunction for an extern, static, or automatic object, the program will probably crash as soon as the delete stateme nt executes. There is no portable way for an objectto tell that it was instantiated on the heap, so the class cannot assert that itsobject is properlyin s

54、ta ntiated.Sec ond, whe n an object commits suicide this way,the using program might not knowabout its demise 死亡 / 轉(zhuǎn)讓.As far as thein sta ntiati ngprogram is concerned 有關(guān)的,the object rema ins in scope and continuesto exist even though the object did itself in. Subsequent后來的 dereferencing間接引用(derefer

55、encing pointer?重引用指針,dereferencing operator?取值運算符)of the poin ter can and usually does lead to disaster不幸.You should n ever do this. Since compiler does not know whether the object was allocated on the stack or on the heap, delete this could cause a disaster.How virtual fun cti ons are impleme nted執(zhí)

56、行 C+?Virtual functions are implemented using a table of function pointers, called the vtable. There is one entry in the table per virtual function in the class. This table is created by the constructor of the class. When a derived class is constructed, its base class is constructed first which creat

57、es the vtable. If the derived class overrides any of the base classes virtual functions, those en tries in the vtable are overwritte n by the derived class con structor. This is why youshould never call virtualfunctions from a constructor: because the vtable entries for the object may not have bee n

58、 set up by the derived class con structor yet, soyou might end up calli ng base class impleme ntati ons of those virtual functionsWhat is n ame man gli ng in C+?The process of en codi ng the parameter types with the fun ctio n/method n ame into a unique n ame is called n ame man gli ng. The in verse

59、 process is called dema ngli ng.For example Foo:bar(i nt, I ong) const is man gled as bar_C3Fooil.For a con structor, the method n ame is left out. That is Foo:Foo(i nt, I ong) constis man gled as _C3Fooil.What is the differe nee betwee n a poin ter and a refere nee?A referenee must always refer to

60、some object and, therefore, must always be in itialized; poin ters do not have such restrict ions. A poin ter can be reassig ned to point to differe nt objects while a refere nee always refers to an object with which it was in itialized.How are prefix and postfix versi ons of operator+() differe nti

溫馨提示

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

評論

0/150

提交評論