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

下载本文档

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

文档简介

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(展现) differentbehaviors.You can use impl

4、ementation (实现)inheritaneeto achieve polymorphism in Ianguagessuch as C+ and Java.Base class objects poin ter can inv oke(调用) 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?不经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实现 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 )抛出异常时,将暂停当前函数的执行,开始查找匹配的catch子句。首先检查throw本身是否在try块内部,如果是,检查与该try相关的catch子句,看是否可以处理该异常。 如果不能处理,就退出当前

41、函数,并且释放当前函数的内存并销毁局部对象,继续到上层 的调用函数中查找,直到找到一个可以处理该异常的catch。这个过程称为栈展开(stackunwinding )。当处理该异常的catch结束之后,紧接着该catch之后的点继续执行。为局部对象调用析构函数如上所述,在栈展开的过程中,会释放局部对象所占用的内存并运行类类型局部对象的析 构函数。但需要注意的是,如果一个块通过new动态分配内存,并且在释放该资源之前发生异常,该块因异常而退出,那么在栈展开期间不会释放该资源,编译器不会删除该指针, 这样就会造成内存泄露。析构函数应该从不抛出异常在为某个异常进行栈展开的时候,析构函数如果又抛出自己

42、的未经处理的另一个异常,将 会导致调用标准库terminate函数。通常terminate函数将调用abort函数,导致程序的 非正常退出。所以析构函数应该从不抛出异常。异常与构造函数如果在构造函数对象时发生异常,此时该对象可能只是被部分构造,要保证能够适当的撤 销这些已构造的成员。未捕获的异常将会终止程序不能不处理异常。如果找不到匹配的catch,程序就会调用库函数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.标准容器类特点顺序性容器vector从后面快速的拉入与删除,直接访问任何元素deque从前面或后面快速的插入与删除.直接访问任何元索list双链表,从任何地方快速插入与删除关联容器set快速杳找.不允许重复值multiset快速查找,允许重复他map一对多映愆基丁咲键手快速杳找,不允许重复倩multimap一对多映射,甚于关键字快速查找,允许重夏值容器适配器stack后进先出queue先进先出priority_queue最高优先级元素总是第一个出列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.使用预处理器实现,没有了参数压栈,代码生成等一系

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陷阱/ 误区.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 死亡 / 转让.As far as thein sta ntiati ngprogram is concerned 有关的,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执

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

评论

0/150

提交评论