Home  >  Article  >  Backend Development  >  Selected C++ interview questions that you must understand

Selected C++ interview questions that you must understand

php是最好的语言
php是最好的语言Original
2018-08-06 16:13:212691browse

C Essence of interview questions

1., why can’t the constructor Declared as virtual function?

Analysis: Because the virtual function uses the method of virtual calling, virtual calling refers to the working mechanism that allows

to only know part of the information. , specifically allows us to call a function that only knows the interface but not the exact type of its object.

But if we want to call the constructor to create an object, we must know the exact type of the object,

So the constructor cannot be a virtual function.

2.C Which functions in ## cannot be declared virtual function?

Analysis: ordinary functions (non-member functions), constructors, inline member functions, static member functions, and friend functions.

(1) Virtual functions are used for base classes and derived classes, ordinary functions cannot be

(2) Constructors cannot be used because virtual functions use virtual calling methods,

(3) The essence of inline member functions is to directly expand the code at the place of call

(4) When inheriting, static member functions cannot be inherited, because they only belong to one class, because There is no dynamic linking

(5) The friend function is not a member function of the class, so it cannot be inherited

3## .#What is the difference between static members and non-static members of a class? Answer: Each class has only one static member. Static members are shared by instance objects of all classes. Static members include static member variables and static member functions. Static members Variables must be initialized before use. Static member variables can be accessed by static member functions and non-static member functions, while static member functions can only access static member variables because static member functions belong to classes and do not have this pointers. Every object has one non-static member.

4 What is the difference between overloading and overriding (some books also call it "overwriting")? Overloading: refers to allowing multiple functions with the same name, but the parameter lists of these functions are different (perhaps the number of parameters is different, or the parameter types are different, or both different). Rewriting: refers to the method by which a subclass redefines a virtual function of a complex class. From the implementation principle: overloading: the compiler modifies the names of functions with the same name based on different parameter lists of the functions, and then these functions with the same name become different functions (at least for the compiler). For example, there are two functions with the same name: function func (p: integer): integer; and function func (p: string): integer;. Then the function names modified by the compiler may be like this: int_func, str_func. The calls to these two functions have been determined between compilers and are static. In other words, their addresses are bound at compile time (early binding), therefore, overloading has nothing to do with polymorphism! Rewriting: Really relevant to polymorphism. When a subclass redefines the virtual function of the parent class, the parent class pointer dynamically calls the function belonging to the subclass according to the different subclass pointers assigned to it. Such function calls cannot be determined during compilation (call The address of the virtual function of the subclass cannot be given). Therefore, such function addresses are bound at runtime (late binding)

5 Briefly describe the differences between member functions, global functions and friend functions. Member functions can only be called by objects instantiated by this class. [Except static members]

Global functions can be called anywhere.

Friend functions can be called by objects of this class and friend classes.

Use delete to delete the memory allocated with new. Delete the memory allocated with new[] using delete[]. delete[] will call the destructor of the array element. Internal data types don't have destructors, so it's not a big problem. If you use delete without parentheses, delete will think it points to a single object, otherwise, it will think it points to an array.

#6. Advantages and disadvantages of inheritance.

Class inheritance is statically defined at compile time and can be used directly. Class inheritance can more easily change the implementation of the parent class. But class inheritance also has some shortcomings. First, because inheritance is defined at compile time, the implementation inherited from the parent class cannot be changed at run time. To make matters worse, the parent class usually defines at least part of the behavior of the child class, and any changes to the parent class may affect the behavior of the child class. If the inherited implementation is not suitable to solve the new problem, the parent class must be rewritten or replaced by another more suitable class. This dependency limits flexibility and ultimately reusability. (To be added)

7. What are the properties of C (object-oriented features)

Encapsulation, inheritance and multiple state.

In object-oriented programming languages, encapsulation is a feature that uses reusable components to construct software systems. It not only supports the reusability of the system, but also helps improve the scalability of the system; message passing can achieve Sending a common message while calling different methods; encapsulation is a technique to achieve information hiding, and its purpose is to separate the definition and implementation of a class.

#8. When do you need to use "constant references"?

If you want to use references to improve the efficiency of the program and protect the data passed to the function from being changed in the function, you should use constant references. Constant reference declaration method: const type identifier & reference name = target variable name;

int a

const int &ra=a;

ra=1; //Error

a=1; //Correct

Example 2 string foo();

void bar(string & s);

Then the following expression The formula will be illegal:

bar(foo( ));

bar("hello world");

The reason is that foo() and "hello world" string A temporary object will be generated, and in C, these temporary objects are of const type. Therefore, the above expression is trying to convert a const type object to a non-const type, which is illegal. Reference parameters should be defined as const if they can be defined as const

9. What is ASSERT() used for

Answer: ASSERT() is a macro often used when debugging a program. When the program is running, it evaluates the expression in the brackets. If the expression is FALSE (0),

Program An error will be reported and execution will be terminated. If the expression is not 0, continue executing the following statements. This macro usually determines whether obviously illegal data appears in the program. If so, it terminates the program to avoid serious consequences and also facilitates the search for errors. For example, the variable n should not be 0 in the program. If it is 0, it may cause an error.

10. achieve more Stateful method?

## Analysis: ① A reference to a base class can point to an instance of its derived class

② A pointer to a base class can point to an instance of its derived class

11. Three basic characteristics of object-oriented and simple Narrate it?

① Encapsulation: Abstract objective things into classes, and each class implements access control (private, protected, public) on its own data and methods

② Inheritance: There are three implementation forms of generalized inheritance:

Implementation inheritance (referring to the ability to use the properties and methods of the base class without additional coding)

Visual inheritance (child forms use parent The appearance and implementation code of the form)

Interface inheritance (only properties and methods are used, implementation lags to subclass implementation).

The first two (class inheritance) and the latter (object combination => interface inheritance and pure virtual function) constitute two ways of function reuse.

③ Polymorphism: It is a technology that sets a parent object to be equal to one or more of its child objects. After assignment, the parent object can operate in different ways according to the characteristics of the child objects currently assigned to it. To put it simply, it is one sentence: It is allowed to assign a pointer of a subclass type to a pointer of a parent class type.

Supplementary question: What is the role of polymorphism?

There are two main ones:

1. Hide implementation details so that the code can be modularized; extend code modules to achieve code reuse;

2. Interface reuse: for classes When inheriting and deriving, ensure the correct call when using an attribute of an instance of any class in the family.

12## Overload (overload) and rewrite (overried), some books are also called "cover )?

① Overloading: It means that multiple functions with the same name are allowed to exist, and the parameter lists of these functions are different (maybe the number of parameters is different, maybe the parameter types are different, or both all different).

② Rewriting: refers to the method by which a subclass redefines the virtual function of the parent class.

In terms of implementation principles:

① Overloading: The compiler modifies the names of functions with the same name based on different parameter lists of the functions, and then these functions with the same name become different functions ( At least for the compiler). The call to this type of function is determined during compilation and is static. In other words, their addresses are bound at compile time (early binding), therefore, overloading has nothing to do with polymorphism!

② Rewriting: Really related to polymorphism. When a subclass redefines the virtual function of the parent class, the parent class pointer dynamically calls the function belonging to the subclass according to the different subclass pointers assigned to it. Such function calls cannot be determined during compilation (call The address of the virtual function of the subclass cannot be given). Therefore, such a function address is bound at runtime (late binding)

13What is the role of polymorphism?

There are two main ones:

① Hide implementation details so that the code can be modularized; extend the code module to achieve code reuse;

② Interface reuse: In order to ensure the correct call when using a certain attribute of an instance of any class in the family when the class inherits and derives.

14, empty class in C, default class member function:

class
{
  public:
    Empty();                         // 缺省构造函数
    Empty(const Empty&);             // 拷贝构造函数
    ~Empty();                        // 析构函数
    Empty& operator=(const Empty&);  // 赋值运算符
    Empty* operator&();              // 取值运算符
    const Empty* operator&() const;  // 取值运算符const
};

15. What are the methods of inter-process communication?

Inter-process communication methods include: shared memory, pipes (named pipes/unnamed pipes), Sockets, message queues, signals, semaphores, memory mapping, etc.

16Four necessary conditions for deadlock?

Mutually exclusive, request to maintain, inalienable, loop.

17 What is the difference between static members and non-static members of a class?

#There is only one static member of a class for each class, which belongs to this class; each object of the non-static member of the class has one copy.

18

What is a shallow copy? What is a deep copy?

Shallow copy means that the source object and the copy object share an entity, only the referenced variables are different (different names). Changes to any one object will affect the other object.

Deep copy means that the source object and the copy object are independent of each other, and changes to any one object will not affect the other object.

Generally speaking, a shallow copy is to copy the pointer of that object. A deep copy copies that object.

19##、Windows Several ways to synchronize programming threads? (Important)

Atomic lock, critical section (segment), event, mutex (body), semaphore, waitable timer

20What is "quote"? What issues should we pay attention to when declaring and using "reference"?

Answer: A reference is an "alias" (alias) of a target variable. The operation of the reference has the same effect as the direct operation of the variable. When declaring a reference, remember to initialize it. After the reference is declared, it is equivalent to the target variable name having two names, namely the original name of the target and the reference name. The reference name can no longer be used as an alias for other variable names. Declaring a reference does not define a new variable. It only means that the reference name is an alias of the target variable name. It is not a data type in itself, so the reference itself does not occupy a storage unit, and the system does not allocate storage units to the reference. Unable to create reference to array.

21. What is the difference between a "reference" and a pointer?

#After a pointer points to an object through a pointer variable, it operates indirectly on the variable it points to. The use of pointers in the program makes the program less readable; the reference itself is an alias of the target variable, and the operation on the reference is the operation on the target variable. In addition, there is the difference between passing ref and pointer to functions mentioned above.

22. What is the difference between association, aggregation (Aggregation) and composition (Composition)?

Involves some concepts in UML: association represents a general connection between two classes, such as "student" and "teacher" is an association relationship; aggregation represents The has-a relationship is a relatively loose relationship. The aggregate class does not need to be responsible for the aggregated class. As shown in the figure below, an empty diamond is used to represent the aggregation relationship:

From an implementation perspective, aggregation It can be expressed as:

class A {...} class B { A* a; .....}

And combination represents the relationship of contains-a, and the correlation is stronger than aggregation : The combined class and the combined class have the same life cycle. The combined class is responsible for the combined class. A solid diamond is used to represent the combination relationship:

The implementation form is:

class A{ ...} class B{ A a; ...}

##23.For Three basic characteristics of objects and briefly describe them? 1. Encapsulation: Abstract objective things into classes, and each class implements protection (private, protected, public) for its own data and methods

2. Inheritance: There are three implementation forms of generalized inheritance: implementation inheritance (referring to the ability to use the properties and methods of the base class without additional coding), visual inheritance (the child form uses the appearance and implementation code of the parent form), and interface Inheritance (only properties and methods are used, implementation lags to subclass implementation). The first two (class inheritance) and the latter (object combination => interface inheritance and pure virtual function) constitute two ways of function reuse.

3. Polymorphism: It is a technique of setting a parent object to be equal to one or more of its child objects. After assignment, the parent object can be configured differently according to the characteristics of the child objects currently assigned to it. way to operate. To put it simply, it is one sentence: It is allowed to assign a pointer of a subclass type to a pointer of a parent class type.

24 What is the role of polymorphism? There are two main ones: 1. Hiding implementation details so that the code can be modularized; extending code modules to achieve code reuse; 2. Interface reuse: for classes to use inheritance and When deriving, ensure the correct call when using an attribute of an instance of any class in the family.

25 Why do we need to call a function compiled by the C compiler in a C program? Add extern "C" statement?

//extern is a keyword in C/C language that indicates the scope of functions and global variables. This keyword tells the compiler that the functions and variables it declares can be used in this module or other modules

// extern "C is a connection declaration. When compiling, it tells the compiler that the following code should be compiled and connected in a C-style way. The purpose is to realize mixed programming of C, C and other languages.

26.What is the difference between a "reference" and a pointer?

After a pointer points to an object through a pointer variable, it operates indirectly on the variable it points to. Using pointers in programs makes the program less readable; and the reference itself is the target variable. Alias, the operation on the reference is the operation on the target variable. In addition, it is the difference between passing ref and pointer to the function mentioned above.

23.The connection and difference between New delete and malloc free?

Answer: Both perform dynamic memory operations on the heap. Use The malloc function needs to specify the number of bytes of memory allocation and cannot initialize the object. new will automatically call the object's constructor. delete will call the object's destructor, while free will not call the object's destructor.

24 Characteristics of overloaded member functions:
(1) Same scope (In the same class);
(2) The function name is the same;
(3) The parameters are different;
(4) The virtual keyword is optional.

25##Overwriting means that the derived class function covers the base class function. The characteristics are: (1) Different scopes (located in derived classes and base classes respectively);
(2) The function names are the same;
(3) The parameters are the same;
(4) The base class function must have the virtual keyword .

26## If you use VC to develop a program, there are several common mistakes, C2001, c2005 ,c2011, what are the causes of these errors. In the process of learning VC, the error messages of LNK2001 errors encountered are mainly:

unresolved external symbol "symbol" (undefined external "symbol").

This error message will be generated if the linker cannot find the referenced function, variable or label in all libraries and object files.

Generally speaking, there are two reasons for errors: First, the referenced function or variable does not exist, is spelled incorrectly, or is used incorrectly;

Secondly, different versions of the connection may be used. library.

We often encounter LNK2005 errors in programming - repeated definition errors. In fact, LNK2005 errors are not difficult to solve.

27Introduce STL and explain in detail how STL implements vector. STL (Standard Template Library) is composed of container algorithm iterators.

STL has the following advantages:

It can easily implement a series of algorithms such as searching for data or sorting data;

It is safer and more convenient to debug programs;

You can easily understand even the code written by people using STL under the UNIX platform (because STL is cross-platform).

        Vector is essentially a dynamic array, which will dynamically increase the array space according to the increase of data.

28Introduce templates and containers. How to achieve? (Maybe I will give you an example to implement it on the spot) ## Templates can be said to be relatively old, but the current generic programming is essentially template programming.

It embodies a universal and generalized idea.

STL has 7 main containers: vector, list, deque, map, multimap, set, multiset.

29 : Briefly describe the principle of polymorphic implementation

​​​​​ When the compiler finds that there is a virtual function in a class, it will immediately Generate virtual function table vtable for this class. Each entry in the virtual function table is a pointer to the corresponding virtual function. The compiler also implicitly inserts a pointer vptr into this class (for the vc# compiler, it is inserted into the class ) points to the virtual function table. When calling the constructor of this class, the compiler will implicitly perform the association between vptr and vtable in the class constructor. Code, point vptr to the corresponding vtable, and connect the class with the vtable# of this class ## got in touch. In addition, when the constructor of the class is called, the pointer to the base class has now become the this pointer to the specific class, thus relying on this thisThe pointer can get the correct vtable. Only in this way can we truly connect with the function body. This is dynamic binding and the basic principle of realizing polymorphism.

30: Talk about your understanding of object-oriented

Analysis:Object-oriented can be understood as treating every problem by first determining that the problem consists of several parts, and each part is actually an object. Then design these objects separately, and finally get the entire program. Traditional programming is mostly considered and designed based on functional ideas, while object-oriented programming considers problems based on the object's perspective. Doing so can make the program more concise and clear.

Explanation: The "Object-oriented programming technology" that is most commonly encountered in programming is just It is an integral part of object-oriented technology. Taking advantage of object-oriented technology is a comprehensive technical issue that not only requires object-oriented analysis, design and programming technology, but also requires the help of necessary modeling and development tools.

#31 Why use template classes in C.

Analysis:

1) Can be used to create dynamically growing and decreasing data structures

2) It is type-independent, Therefore it has high reusability.

3) It checks the data type at compile time instead of runtime, ensuring type safety

4) It is platform independent and portable

5) It can be used for Basic data types

#32 What is the difference between function templates and class templates?

Answer: The instantiation of function templates is automatically completed by the compiler when processing function calls, while the instantiation of class templates

Must be explicitly specified by the programmer in the program.

33. What are the main steps to achieve a winsock connection? (Very important, must ask)

Answer: Server side: socker()Establish a socket, bind (bind) and listen (listen), use accept()

Waiting for client connection.

Client: socker()Establish a socket and connect (connect ) server, after connecting, use send() and recv (

) , write and read data on the socket until the data exchange is completed, closesocket()Close the socket.

Server side: accept() finds a client connection, establishes a new socket, and restarts waiting for the connection

catch. The newly generated socket uses send() and recv() to write and read data until the data exchange is completed, closesock

et()Close the socket.

#34 The difference between processes and threads.

Answer: A thread refers to an execution unit within a process and is also a schedulable entity within the process. The difference from a process:

(1) Scheduling : Threads are the basic unit of scheduling and allocation, and processes are the basic units of resource ownership.

(2) Concurrency: Not only processes can be executed concurrently, but multiple threads of the same process can also be executed concurrently.

(3) Own resources: A process is an independent unit that owns resources. Threads do not own system resources, but they can access resources belonging to the process.

(4) System overhead: When creating Or when canceling a process, because the system has to allocate and reclaim resources for it, the system overhead is significantly greater than the overhead when creating or canceling threads.

35. Is C type-safe?

Answer: No. Two pointers of different types can be cast (using reinterpret cast). C# is type safe.

  1. If you use VC to develop a program, there are several common errors, C2001, c2005, c2011, what are the reasons for these errors.

37 The difference between macros and inline functions

Analysis: Both inline functions and macros are expanded where the program appears. Inline functions are not implemented through function calls. They are expanded at the program that calls the function (completed during compilation); macros are also ;

The difference is that inline functions can complete compilation functions such as type detection and whether statements are correct during compilation; macros do not have such functions, and the macro expansion time is different from that of inline functions. (Expand during runtime)

#38 Where is the entry point of the message loop Windows program in win32? Write the process of Windows message mechanism

# Analysis: The entry point of Windows program is the WinMain() function.

Windows application message processing mechanism:

A. The operating system receives the window message of the application and delivers the message to the application's message queue

B. Application The program calls the GetMessage function in the message loop to retrieve messages one by one from the message queue. After retrieving the messages, the application can perform some preprocessing on the messages.

C. The application calls DispatchMessage to send the message back to the operating system.

D. The system uses the pointer to the window procedure function saved in the lpfnWndProc member of the WNDCLASS structure to call the window procedure to process the message.

39: Talk about your understanding or knowledge of programming specifications

Programming specifications can be summarized as: Program Feasibility, readability, portability and testability.

Note: This is the general outline of programming specifications. Interviewers do not have to recite the examples given above. They should understand the problems illustrated by these examples and think about how they can solve the feasibility and The questions of readability, portability and testability are combined with the above examples and your usual programming habits to answer this question.

40 Why do stream operator overloads return references

##In the program, the stream operators >> and < ;97f5d399bace9e269ef136348e831fe2"

D. Ternary operator "? :"

Analysis: There is no reason why ABD will not work

2.

In the following description of C classes, the incorrect one is A.C language introduced classes mainly play two roles, as a data encapsulation mechanism and As a type definition mechanism

The data and functions defined in the B.C class are called data members and member functions respectively

As a data encapsulation mechanism, the C.C class organizes data and operations on the data to achieve information hiding.

The members in the D.C class can be divided into four types: public members, protected members, and private Members and friends

Correct answer:D

3. With int x = 123, the statement produces output of the form "123" ("" represents a space).

## A.cout aa3cfadbfa7f73fcc4d55c84cb07969e class Sample {…};
B.template1bbcbf404aff658cf5eed197e6af2bc7 class Sample {…} ;

C.template8c49dd555a9806de561d35e83b4ae27d class Sample {…};

D.template17441c4bf03cd3139b4c9059754f3614 Sample {…};

Correct answer: C

5

Non-C built-in types A and B, under what circumstances Can B be implicitly converted to A? [C Medium] a. class B : public A { ……}b. class B { operator A( ); }c. class A { A ( const B& ); }
d. A& operator= ( const A& );

Analysis: The first item, B, is publicly inherited from A and can be inherited indirectly. The second item: B implements the implicit conversion to A

The third item: A implements the non-explicit parameter as B (can have other parameters with default values) constructor

Four items: Assignment operation, although it is not an authentic implicit type conversion, it can still be regarded as one


6

The wrong statement about this pointer is (A)

  1. ##This pointer must display the description                                                                                                                                                                                             ​

    1. ##Member functions have this pointer   Own this pointer

    2. ##7.

    3. In the following function prototype declaration, (B) declares fun as a pure virtual function
    4. A . void fun()=0;
    5. ##B virtual void fun()=0;

      C virtual void fun();
    6. D virtual void fun(){};

8

Friend operator obj>obj2 is interpreted by the C compiler as (A).

# operator>(obj1,obj2)

>(obj1,obj2)## obj2. operator>(obj1)

  1. # obj1.oprator>(obj2)

    1. # #

9.假定AB为一个类,则执行“AB a(4),b[3],*p[2];”语句时,自动调用该类构造函数的次数为:B

A) 3  B) 4  C) 6   D) 9

10.假定要对类AB定义加号操作符重载成员函数,实现两个AB类对象的加法,并返回相加结果,则该成员函数的声明语句为:B

A) AB operator+(AB &a,AB &b)

B) AB operator+(AB &a)

C) operator+(AB a)             

D) AB & operator+()

11.有二维字符数组char s[4][6]={"zhang","gao","tang","wang"};执行程序coutdaeeae8786145a0c6601e10ab13634c6打印结果是多少

 using namespace std;
   class A1{
   public:
    int a;
    static int b;
    A1();
    ~A1();
   };
   int main()   {
    cout << sizeof(A1) <<endl;
   }

         解析:是4, 静态变量是存放在全局数据区的, 而sizeof是计算局部栈中分配的大小。

13.死锁的处理

  解析:鸵鸟策略、预防策略、避免策略、检测与解除死锁,只要知道概念就行,不需要掌握

14. 非C++内建型别 A 和 B,在哪几种情况下B能隐式转化为A?[C++中等]

解析:a. class B : public A { ……} // B公有继承自A,可以是间接继承的

     b. class B { operator A( ); } // B实现了隐式转化为A的转化

    c. class A { A( const B& ); } // A实现non-explicit的参数为B(可有其他带默认值的参数)构造函数

    d. A& operator= ( const A& ); // 赋值操作,虽不是正宗的隐式类型转换,但也可以勉强算一个

15以下代码有什么问题?[STL易]

typedef vector IntArray;

IntArray array;

array.push_back( 1 );

array.push_back( 2 );

array.push_back( 2 );

array.push_back( 3 );

// 删除array数组中所有的2

for( IntArray::iterator itor=array.begin(); itor!=array.end(); ++itor )

{

    if( 2 == *itor ) array.erase( itor );

}

    解析:其实里面隐藏着一个很严重的错误:当veci.erase(iter)之后,iter就变成了一个野指针,对一个野指针进行 iter++ 是肯定会出错的。

16 下列代码的输出值是多少?

class A{};

class A1{};

class B : public A{};

class C : public A, public A1{};

class D : public virtual A{};

cout << sizeof ( A ) << endl;

cout << sizeof ( B ) << endl;

cout << sizeof ( C ) << endl;

cout << sizeof ( D ) << endl;

Analysis: Answer: 1 , 1, 1, 4 explain: the space occupied by the empty class is 1, the empty class space of single inheritance is also 1, and the empty class space of multiple inheritance is still 1, but virtual inheritance involves virtual tables (virtual pointers), so the size is 4.

Related articles:

Share 125 basic C# interview questions and answers

Interview question one, interview question

The above is the detailed content of Selected C++ interview questions that you must understand. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn