C常見(jiàn)英文面試筆試題_第1頁(yè)
C常見(jiàn)英文面試筆試題_第2頁(yè)
C常見(jiàn)英文面試筆試題_第3頁(yè)
已閱讀5頁(yè),還剩10頁(yè)未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

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

文檔簡(jiǎn)介

1、C/C+ProgramminginterviewquestionsandanswersBy Satish Shetty, July 14th, 2004What is encapsulation?Containingand hidinginformationabout an object,such as internaldata structuresand code. Encapsulation isolates(使隔離 ) the internal complexity of an object'soperationfrom the restof the application.Fo

2、r example,a clientcomponent askingfor net revenue(收益)from a business object need not know the data's origin.What is inheritance?Inheritance allows one class to reuse the state and behavior of another class. The derived class inherits the properties and method implementations of the base class an

3、d extends it by overriding methods and adding additional properties and methods.What is Polymorphism?Polymorphismallowsa clientto treatdifferentobjectsin the same way even iftheywere created from different classes and exhibit(展現(xiàn))different behaviors.You can use implementation(實(shí)現(xiàn))inheritanceto achieve

4、 polymorphismin languagessuch as C+ and Java.Base class object's pointer can invoke(調(diào)用) methods in derived class objects.You can also achieve polymorphism in C+ by function overloading and operator overloading.What is constructor or ctor?Constructor creates an object and initializes it. It also

5、creates vtable 表? 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 constructor?Constructor with no arguments or all the arguments has default values.What is copy construct

6、or?Constructor which initializes the it's with another object of the same class.object member variables ( by shallow copying) If you don't implement one in your class thencompiler implements one for you.for example:Boo Obj1(10); / calling Boo constructorBoo Obj2(Obj1); / calling boo copy con

7、structorBoo Obj2 = Obj1;/ calling boo copy constructorWhen are copy constructors called?Copy constructors are called in following cases:a) when a function returns an object of that class by valueb) when the object of that class is passed by value as an argument to a functionc) when you construct an

8、object based on another object of the same classd) When compiler generates a temporary objectWhat is assignment operator?Default assignment operator handles assigning one object to another of the same class. Member to member copy (shallow copy)What are allthe functionsthe implicitmemberfunctionswhic

9、h compilerimplements forof the us ifclass? we don'tOr what are alldefineone.?default ctorcopy ctorassignment operatordefault destructoraddress operatorWhat is conversion constructor?constructor with a single argument makes that constructor as conversion ctor and it can be used for type conversio

10、n.for example:class Boopublic:Boo( int i );Boo BooObject = 10 ; / assigning int 10 Boo objectWhat is conversion operator?class can have a public method for specific data type conversions.for example:class Boodouble value;public:Boo(int i )operator double()return value;Boo BooObject;double i = BooObj

11、ect; / assigning object to variable i of type double. now conversion operator gets called to assign the value.What is diff between malloc()/free() and new/delete?malloc allocates memory for object in heap but doesn't invoke object's constructor to initiallize the object.new allocates memory

12、and also invokes constructor to initialize the object.malloc() and free() do not support object semanticsDoes not construct and destruct objectsstring * ptr = (string *)(malloc (sizeof(string)Are not safeDoes not calculate the size of the objects that it constructReturns a pointer to voidint *p = (i

13、nt *) (malloc(sizeof(int);int *p = new int;Are not extensiblenew and delete can be overloaded in a class"delete" first calls the object's termination routine (i.e. its destructor) and then releases the space the object occupied on the heap memory. If an array of objectswas created usin

14、g new, then delete must be told that it is dealing with an array by preceding the name with an empty :-Int_t *my_ints = new Int_t10;.delete my_ints;what is the diff between "new" and "operator new" ?"operator new" works like malloc.What is difference between template an

15、d macro?There is no way for the compiler to verify that the macro parameters are of compatible types. The macro is expanded without any special type checking.If macro parameter has a post-incremented variable ( like c+ ), the increment is performed two times.Because macros are expanded by the prepro

16、cessor,compilererrormessages willreferto the expanded macro, ratherthan the macro definitionitself.Also,the macro willshow up in expanded form during debugging.for example:Macro:#define min(i, j) (i < j ? i : j)template:template<class T>T min (T i, T j)return i < j ? i : j;What are C+ st

17、orage classes?autoregisterstaticexternauto: the default. Variables are automatically created and initialized when theyare defined and are destroyed at theend of theblock containing their definition.They are not visible outside that blockregister:a type ofautovariable.a suggestiontothe compilerto use

18、 a CPUregisterfor performancestatic:a variable thatis known only in the functionthat contains itsdefinitionbut is never destroyed and retains=keep its value between calls to that function.It exists from the time the program begins executionextern: a static variable whose definition and placement is

19、determined when allobjectand librarymodules are combined (linked)to form theexecutablecode file.It can be visible outside the file where it is defined.What are storage qualifiers in C+ ?They are.constvolatilemutableConst keyword indicates that memory once initialized, should not be altered by a prog

20、ram.volatilekeyword indicatesthatthe value in the memory locationcan be alteredthough nothing in the programcode modifies the contents. forexample if youhave a pointer to hardware locationeventhat contains the time, where hardware changes the value of this pointer variableand not the program.The int

21、entof thiskeyword to improvethe optimizationabilityof the compiler.mutable keyword indicates that particular member of a structure or class can bealtered even if a particular structure variable, class, or class member functionis constant.struct datachar name80;mutable double salary;const data MyStru

22、ct = "Satish Shetty", 1000 ; /initlized by complierstrcpy ( MyS, "Shilpa Shetty"); / compiler errorMyStruct.salaray = 2000 ; / complier is happy allowedWhat is reference ?reference is a name that acts as an alias, or alternative name, for a previously defined variable o

23、r an object.prepending variable with "&" symbol makes it as reference.for example:int a;int &b = a;& 讀 ampWhat is passing by reference?Method ofpassingargumentsto a functionwhich takesparameterof typereference.for example:void swap( int & x, int & y )int temp = x;x = y;

24、y = temp;int a=2, b=3;swap( a, b );Basically, inside the function instead they refer to original arguments and it is more efficient.therewon'tbe any copy ofthe arguments "x"and "y"variablesa and b. so no extramemory needed to passWhen do use "const" reference argume

25、nts in function?a) Using const protects you against programming errors that inadvertently不經(jīng)意的 alter data.b) Using const allowsfunctionto processboth constand non-constactualarguments,whilea functionwithoutconstintheprototypecan onlyacceptnon constantarguments.c) Using a const reference allows the fu

26、nction to generate and use a temporary variable appropriately.When are temporary variables created by C+ compiler?Providedthatfunctionparameterisa"constreference",compilergeneratestemporary variable in following 2 ways.a) The actual argument is the correct type, but it isn't Lvalue dou

27、ble Cube(const double & num)num = num * num * num; return num;double temp = 2.0;double value = cube(3.0 + temp); / argument is a expression and not a Lvalue;b) The actual argument is of the wrong type, but of a type that can be convertedto the correct typelong temp = 3L;double value = cuberoot (

28、 temp); / long to double conversionWhat is virtual function?Whenderived class overrides the base class method by redefining the same function, then if client wants to access redefined the method from derived class through apointer from base class object, then you must define this function in base cl

29、assas virtual function.class parentvoid Show()cout << "i'm parent" << endl;class child: public parentvoid Show()cout << "i'm child" << endl;parent * parent_object_ptr = new child;parent_object_ptr->show() / calls parent->show() inow we goto v

30、irtual world.class parentvirtual void Show()cout << "i'm parent" << endl;class child: public parentvoid Show()cout << "i'm child" << endl;parent * parent_object_ptr = new child;parent_object_ptr->show() / calls child->show()What is pure virtu

31、al function? or what is abstract class?When you defineonlyfunctionprototypeina base classwithoutimplementationanddo the complete implementation實(shí)現(xiàn) in derived class. This base class is calledabstractclassand clientwon'table to instantiatean objectusingthisbase class.You can make a pure virtual fun

32、ction or abstract class this way.class Boovoid foo() = 0;Boo MyBoo; / compilation errorWhat is Memory alignment?The term alignment primarily means the tendency 趨向 of an address pointer be a multiple of some power of two. So a pointer with two byte alignment hasvaluetoa zeroin the least significant b

33、it. And a pointer with four byte alignment has a zero inboth the two leastsignificantbits.And so on. More alignmentmeans a longersequenceof zero bits in the lowest bits of a pointer.What problem does the namespace feature solve?Multiple providersoflibrariesmight use commonglobalidentifierscausinga n

34、amecollision when an application tries to link with two or more such libraries. Thenamespacefeaturesurroundsa library'sexternaldeclarationswith auniquenamespace that eliminates消除 the potential for those space identifier namespace-body A namespace declaration identifies and assigns

35、 a name to a declarative region.The identifierina namespace declarationmust be uniquein the declarativeregionin which it is used. The identifier is the name of the namespace and is used to reference its members.What is the use of 'using' declaration?A using declaration makes it possible to u

36、se a name from a namespace without the scope 范圍 operator.What is an Iterator迭代器 class?A classthatis used totraversethrough穿過(guò) theobjectsmaintainedby a containerclass. There are five categories of iterators: input iterators, output iterators,forwarditerators,bidirectionaliterators,random access. An it

37、eratoris an entitythat givesaccesstothecontentsofacontainerobjectwithoutviolatingencapsulation constraints. Access to the contents is granted on a one-at-a-timebasis in order. The order can be storage order (as in lists and queues) or somearbitrary order (as in array indices) or according to some or

38、dering relation (asin an orderedbinarytree).The iteratorisa construct,whichprovidesan interfacethat, when called, yields either the next element in the container, or some valuedenoting the fact that there are no more elements to examine. Iterators hide thedetailsof access to and updateof the element

39、sofa containerclass.Something likea pointer.What is a dangling懸掛pointer?A dangling pointer arises when you use the address of an object after its lifetime is over. This may occur in situations like returning addresses of the automaticvariablesfrom a functionor using the address of the memory blockaf

40、teritis freed.What do you mean by Stack unwinding?It is a process during exception handlingwhen the destructor iscalled for alllocalobjects in the stack between the place where the exception was thrown and where itis caught.拋出異常與棧展開(kāi)( stack unwinding)拋出異常時(shí), 將暫停當(dāng)前函數(shù)的執(zhí)行,開(kāi)始查找匹配的 catch 子句。首先檢查 throw本身是否在

41、 try 塊內(nèi)部,如果是,檢查與該try 相關(guān)的 catch 子句,看是否可以處理該異常。如果不能處理, 就退出當(dāng)前函數(shù), 并且釋放當(dāng)前函數(shù)的內(nèi)存并銷(xiāo)毀局部對(duì)象,繼續(xù)到上層的調(diào)用函數(shù)中查找,直到找到一個(gè)可以處理該異常的catch 。這個(gè)過(guò)程稱(chēng)為棧展開(kāi)(stackunwinding )。當(dāng)處理該異常的 catch結(jié)束之后,緊接著該 catch 之后的點(diǎn)繼續(xù)執(zhí)行。1. 為局部對(duì)象調(diào)用析構(gòu)函數(shù)如上所述, 在棧展開(kāi)的過(guò)程中,會(huì)釋放局部對(duì)象所占用的內(nèi)存并運(yùn)行類(lèi)類(lèi)型局部對(duì)象的析構(gòu)函數(shù)。 但需要注意的是, 如果一個(gè)塊通過(guò) new 動(dòng)態(tài)分配內(nèi)存, 并且在釋放該資源之前發(fā)生異常,該塊因異常而退出, 那么在棧展開(kāi)

42、期間不會(huì)釋放該資源, 編譯器不會(huì)刪除該指針, 這樣就會(huì)造成內(nèi)存泄露。2.析構(gòu)函數(shù)應(yīng)該從不拋出異常在為某個(gè)異常進(jìn)行棧展開(kāi)的時(shí)候,析構(gòu)函數(shù)如果又拋出自己的未經(jīng)處理的另一個(gè)異常,將會(huì)導(dǎo)致調(diào)用標(biāo)準(zhǔn)庫(kù) terminate 函數(shù)。通常 terminate 函數(shù)將調(diào)用 abort函數(shù),導(dǎo)致程序的非正常退出。所以析構(gòu)函數(shù)應(yīng)該從不拋出異常。3.異常與構(gòu)造函數(shù)如果在構(gòu)造函數(shù)對(duì)象時(shí)發(fā)生異常,此時(shí)該對(duì)象可能只是被部分構(gòu)造,要保證能夠適當(dāng)?shù)某蜂N(xiāo)這些已構(gòu)造的成員。4.未捕獲的異常將會(huì)終止程序不能不處理異常。如果找不到匹配的catch ,程序就會(huì)調(diào)用庫(kù)函數(shù)terminate 。Name the operators that

43、 cannot be overloaded?sizeof, ., .*, .->, :, ?:What is a container class? What are the types of container classes?A containerclassis a classthatisused to hold objects in memoryor externalstorage.A container class acts as a generic holder. A container class has a predefinedbehaviorand a well-known

44、interface.A container classis a supportingclass whosepurpose is to hide the topologyused formaintainingthelistof objectsinmemory.When a container class contains a group of mixed objects, the container is calleda heterogeneous不均勻的多樣的container;when thecontaineris holdinga group ofobjects that are all

45、the same, the container is called a homogeneous單一的均勻的 container.What is inline function?The _inline keyword tells the compiler to substitute替代 the code within thefunction definition for every instance of a function call. However, substitutionoccurs only at the compiler's discretion 靈活性 . For exa

46、mple, the compiler does not inline a function if its address is taken or if it is too large to inline.使用 預(yù)處理器 實(shí)現(xiàn),沒(méi)有了 參數(shù)壓棧, 代碼生成 等一系列的操作 , 因此, 效率很高, 這是它在 C 中被使用的一個(gè)主要原因What is overloading?With the C+ language,you can overloadfunctionsand operators.Overloadingisthepracticeof supplyingmore than one defi

47、nitionfora givenfunctionname in the samescope.- Any two functions in a set of overloaded functions must have different argument lists.- Overloading functions with argument lists of the same types, based on return type alone, is an error.What is Overriding?To override a method, a subclass of the clas

48、s that originally declared the methodmust declare a method with the same name, return type (or a subclass of that return type), and same parameter list.The definition of the method overriding is:· Must have same method name.· Must have same data type.· Must have same argument list.Ove

49、rridinga method means thatreplacinga method functionalityimplyoverridingfunctionalitywe need parentand childclasses.in child class. To In the child classyou define the same method signature as one defined in the parent class.What is "this" pointer?The thispointeris a pointer accessibleonly

50、withinthememberfunctionsof a class,struct,oruniontype.Itpointstotheobjectforwhichthememberfunctioniscalled.Static member functions do not have a this pointer.Whena non-staticmember functioniscalled for an object,the addressoftheobjectis passed as a hiddenargumenttothefunction.Forexample, thefollowin

51、gfunctioncallmyDate.setMonth( 3 );can be interpreted解釋 this way:setMonth( &myDate, 3 );The object'saddressisavailablefrom withinthememberfunctionas thethispointer.It is legal,though unnecessary, touse the this pointer when referringto membersof the class.What happens when you make call "delete this;" ?The code has two built-in pitfalls陷阱 / 誤區(qū) . First, if it executes in a memberfunctionfor an extern, static,or automaticobj

溫馨提示

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

最新文檔

評(píng)論

0/150

提交評(píng)論