Search for C ++ interview materials and answer questions (1)

Source: Internet
Author: User

 

1. Why should I add the extern "C" to call the function compiled by the C compiler in the C ++ program "?
A: First, extern is a keyword in the C/C ++ language that indicates the range of the function and global variable. This keyword tells the compiler that, the declared functions and variables can be used in this module or other modules.
In general, the function and global variables referenced by this module to other modules are declared with the keyword extern in the module header file. Extern "C" is a linkage declaration. Variables and functions modified by extern "C" are compiled and connected in C language. As an object-oriented language, C ++ supports function overloading, while Procedural Language C does not. The name of the function in the symbol library after being compiled by C ++ is different from that in the C language. For example, assume that the prototype of a function is void Foo (int x, int y). After the function is compiled by the C compiler, its name in the symbol library is _ Foo, the C ++ compiler generates names such as _ foo_int_int. Such a name contains the function name, number of function parameters, and type information. c ++ relies on this mechanism to implement function overloading.
Therefore, we can summarize the true purpose of the extern "C" statement in one sentence: To solve the name matching problem and implement mixed programming of C ++ and C.

2. What is the role of ifndef/define/endif in the header file?

A: This is a header file protection character pre-compiled by C ++. Ensure that the header file is defined only once even if the file is contained multiple times.

3. What is the difference between # include <file. h> and # include "file. H?
A: The former searches for and references file. h from the standard library path, and the latter searches for and references file. h from the current working path.

4. Evaluate the features of C/C ++

A: C is a structured language oriented to processes. Based on algorithms and data structures, the C language considers how to output data from input through a process or function;

C ++ Is Object-Oriented. Based on classes, objects, and inheritance, it considers how to construct an object model so that this model can fit the corresponding problems, get the output or implement process control by obtaining the object status information.

5. What is the purpose of const?

A: In C/C ++, (1) You can define const constants, and (2) modify the return values and parameters of functions;

In C ++, you can also modify the definition body of a function and define the const member function of the class. Things modified by const are forcibly protected to prevent unexpected changes and improve program robustness.

6. What is the difference between const and # define?

A: (1) Both const and # define can define constants, but const is more widely used.

(2) const constants have data types, while macro constants do not. The compiler can perform type security checks on the former. However, only character replacement is performed for the latter, and there is no type security check, and unexpected errors may occur during character replacement.
(3) Some integrated debugging tools can debug const constants, but cannot debug macro constants.

7. About sizeof summary.

A: sizeof calculates the memory size allocated in the stack.

(1) sizeof does not calculate the memory occupied by static variables;

(2) the pointer size must be 4 bytes, no matter what type of pointer;

(3) Char occupies 1 byte, int occupies 4 bytes, and short int occupies 2 bytes.

Long int occupies 4 bytes, float occupies 4 bytes, double occupies 48 bytes, and string occupies 4 bytes.

An empty class occupies 1 byte, and a single inherited empty class occupies 1 byte. The virtual inheritance involves a virtual pointer, so it occupies 4 bytes.

(4) Length of the array:

If the length of the array is specified, the number of elements is not counted. The total number of bytes = array length * sizeof (element type)

If no length is specified, it is determined based on the actual number of elements.

PS: if it is a character array, it should take into account the null character at the end.

(5) Length of struct object

By default, to facilitate access and management of elements in the structure body, when the length of elements in the Structure Body is smaller than the number of processor digits, the Unit is aligned with the length of the longest Data Element in the structure, which is an integer multiple of the elements. If the element length in the structure is greater than the number of processors, the elements are aligned in units of the number of processors.

(6) unsigned only affects the meaning of the highest bit, and the data length does not change, so sizeof (unsigned INT) = 4

(7) The value of sizeof of the custom type is equal to the value of sizeof the type prototype.

(8) When sizeof is used for a function, it will be replaced by the type returned by the function in the compilation phase.

(9) after sizeof, if it is a type name, it must be enclosed in parentheses. If it is a variable name, it can be left blank because sizeof is an operator.

(10) When the structure type or variable is used, sizeof returns the actual size. When a static array is used, all sizes of the array are returned. sizeof cannot return the size of a dynamic array or an external array.

8. What is the difference between sizeof and strlen?

Answer: (1) the type of sizeof returned value is size_t (unsigned INT );

(2) sizeof is an operator, while strlen is a function;

(3) sizeof can be a type parameter. Its parameters can be any type or variables or functions, while strlen can only be a char * parameter and must end with '\ 0;

(4) When an array is used as a sizeof parameter, It is not degraded to a pointer, but passed to strlen is degraded to a pointer;

(5) sizeo is a constant during compilation, and strlen is calculated only at runtime, and the number of characters in the string is not the memory size;

9. What is the difference between a pointer and a reference?

A: Both pointers and references provide the function of indirectly manipulating objects.

(1) the pointer definition can not be initialized, but the reference must be initialized at the definition. It is bound to an object. Once bound, as long as the reference exists, it will always be bound to this object;

(2) differences in the assignment behavior: the pointer assignment is to direct the pointer to another object, while the reference assignment is to modify the object itself;

(3) There is a type conversion between pointers. The reference is divided into const references and non-const applications. Non-const references can only be bound to objects of the same type, the const reference can be bound to objects of different but related types or the right value.

10. What is the difference between arrays and pointers?

A: (1) arrays are created either in the global data zone or on the stack. pointers can be directed to any type of memory block at any time;

(2) differences in the modified content:

Char A [] = "hello ";
A [0] = 'X ';
Char * P = "world"; // note that P points to a constant string
P [0] = 'X'; // This error cannot be found by the compiler. It is a runtime error.

(3) the sizeof operator can be used to calculate the array capacity (number of bytes ). Sizeof (P), P is the number of bytes of a pointer variable, rather than the memory capacity referred to by P. C ++/C language cannot know the memory capacity referred to by the pointer unless you remember it when applying for memory. Note: When an array is passed as a function parameter, the array will automatically degrade to a pointer of the same type.

11. What is the difference between a null pointer and a hanging pointer?

A: a null pointer refers to a pointer with a null value. A hanging pointer is generated when Delete points to a dynamically assigned object.

(1) The NULL pointer can be deleted multiple times, and the program becomes unstable when the suspension pointer is deleted again;

(2) The use of the NULL pointer and the suspension pointer are both illegal, and may cause program crash. if the pointer is a null pointer, although it is also a crash, but compared with the suspension pointer, It is a predictable crash.

12. There is malloc/free in C ++. Why is there new/delete?

A: malloc/free is a C/C ++ standard library function, and new/delete is a C ++ operator. They can be used to dynamically apply for and release memory.

There is no big difference between built-in data types. When applying for memory for malloc, you must specify the number of bytes for memory allocation without initialization. When applying for new, you can specify initialization by default;

For objects of the class type, malloc/free cannot meet the requirements. The constructor must be automatically executed when the object is created, and the Destructor must be called before it disappears. Since malloc/free is a library function rather than an operator and is not controlled by the compiler, you cannot impose the tasks for executing constructor and destructor on it. Therefore, c ++ also requires new/Delete.

13. What is smart pointer?

A: When there are pointer members in a class, there are two methods to manage pointer members: one is to manage pointer members in a value-type mode, each class Object retains a copy of the object to which the Pointer Points. Another more elegant way is to use a smart pointer to share the object to which the Pointer Points.

A common implementation technology of smart pointers is the use of reference counting. The smart pointer class associates a counter with the object to which the class points. The reference counting class tracks how many objects in the class share the same pointer.

Each time a new object of the class is created, the pointer is initialized and the reference count is set to 1. when an object is created as a copy of another object, copy the constructor to copy the pointer and add the corresponding reference count. when an object is assigned a value, the value assignment operator reduces the reference count of the object indicated by the left operand (if the reference count is reduced to 0, delete the object), and increase the reference count of the object indicated by the right operand. when calling the destructor, the constructor reduces the reference count (if the reference count is reduced to 0, the base object is deleted ).

14. What are the basic concepts and features of object-oriented technology?

A: Basic Concepts: Class, object, and inheritance. Basic Features: encapsulation, inheritance, and polymorphism.

Encapsulation: combines low-level elements to form new and higher entity technologies;
Inheritance: generalized inheritance has three implementation modes: Implementation inheritance, visual inheritance, and interface inheritance.
Polymorphism: assign a pointer of the subclass type to the pointer of the parent class.

15. What member functions does the C ++ empty class have by default?

A: default constructor, destructor, copy constructor, and assign value function

16. Which member variable can be shared among instances of a class?

A: static member variables

17. In the hierarchy of inheritance, why is the basic class destructor a virtual function?

A: The Compiler always calls class member functions based on the type. However, the pointer of a derived class can be safely converted to a pointer of a base class. In this way, when a base class pointer is deleted, C ++ calls the base class destructor instead of the derived class, regardless of whether the pointer points to a base class object or a derived class object. If you rely on the code of the destructor of the derived class to release resources without reloading the destructor, there will be resource leakage.

18. Why cannot constructors be virtual functions?

A: virtual functions use a virtual call method. A call is a mechanism that can work with only partial information. If you create an object, you need to know the exact type of the object. Therefore, the constructor cannot be a virtual function.

19. If the virtual function is valid, why not set all functions as virtual functions?

A: No. First, virtual functions have a cost. Because each virtual function object needs to maintain a virtual function table, a certain amount of system overhead is generated when using virtual functions, this is unnecessary.

20. constructor can be an inline function.

21. What is polymorphism? What is the role of polymorphism?

A: Polymorphism refers to pointing the pointer or reference of the base class type to an object of the derived type. Polymorphism is implemented through the virtual function mechanism.

The role of polymorphism is interface reuse.

22. What is the difference between heavy load and coverage?

A: A virtual function is a function of the base class that you want to redefine In the derived class. The method of redefining the base class virtual function is overwrite;

Overload allows multiple functions with the same name in the same scope. The parameter tables of these functions are different. The concept of overload does not belong to object-oriented programming. The Compiler modifies the names of functions with the same name based on different parameter tables of the function, and then these functions with the same name become different functions.

The confirmation of overload is determined at compilation, and it is static; the confirmation of virtual function is dynamic at runtime.

23. Public inheritance, protected inheritance, and private inheritance

Answer: (1) when public inheritance is implemented, the derived class object can access the public members in the base class, and the member functions of the derived class can access the public and protected members in the base class;

(2) In private inheritance, the base class members can only be accessed by members of the directly derived class and cannot be inherited further;

(3) When the inheritance is protected, the members of the base class are only accessed by members of the direct derived class and cannot be inherited further.

24. Protected members of the base class can be accessed through the derived class object but cannot be modified when the public inherits the class.

25. In which situations can I only use constructors to initialize the list, but not assign values to initialize the list?

Answer: const Member, referencing Member

26. What is a virtual pointer?

A: The virtual pointer or virtual function pointer is the implementation details of the virtual function. Each object with a virtual function has a virtual pointer pointing to the virtual function table of this class.

27. How does C ++ prevent a class from being instantiated? When will the constructor be declared as private?

Answer: (1) define the class as an abstract base class or declare the constructor as private;

(2) class objects cannot be created outside the class. Only objects can be created inside the class.

28. What will be executed before the main function is executed? Can code be executed after execution?

A: (1) the constructor of the global object is executed before the main function;

(2) Yes. You can use _ onexit to register a function. It will be executed after main;

If you need to add a piece of code that is executed after the main exit, you can use the atexit () function to register a function.

Syntax:

# Include <stdlib. h>

# Include <stdio. h>

Int atexit (void (* function ") (void ));

Void fn1 (void), FN2 (void), fn3 (void );

Int main (void)

{

Atexit (fn1 );

Atexit (FN2 );

Printf ("this is executed first. \ n ");

}

Void fn1 ()

{

Printf ("this is \ n ");

}

Void FN2 ()

{

Printf ("executed next .");

}

Result:

This is executed first.

This is executed next.

29. What is the difference between a process and a thread?

A: (1) a process is a program execution and a thread is the execution unit in the process;

(2) processes are independent, which is manifested in the memory space and Context Environment. threads are running in the process;

(3) In general, a process cannot break through the process boundary to access the storage space in other processes, and the thread shared memory space generated by the same process;

(4) Two segments of code in the same process cannot be executed simultaneously, unless multithreading is introduced.

30. How do processes communicate?

Answer: signal, semaphore, message queue, and shared memory

31. What is the difference between multi-process and multi-thread in network programming involving concurrent servers?

A: (1) the thread execution overhead is small, but it is not conducive to resource management and protection. On the contrary, processes can be migrated across machines.

(2) Each process has its own memory space when there are multiple processes, and the memory space is shared among multiple threads;

(3) Fast thread generation, Fast inter-thread communication, and fast switching;

(4) Good thread resource utilization;

(5) synchronization is required when the thread uses public variables or resources.

32. Let's talk about the whole process of TCP three-way handshake and four-way handshake.

33. What is the difference between TCP and UDP.

A:

TCP-the transmission control protocol provides a connection-oriented and reliable byte stream service.

Before the customer and the server exchange data with each other, a TCP connection must be established between the two parties before data can be transmitted. TCP provides timeout resend, discard duplicate data, test data, traffic control, and other functions to ensure data can be transferred from one end to the other.

UDP-User Datagram Protocol is a simple datagram-oriented transport layer protocol. UDP does not provide reliability. It only sends the data from the application to the IP layer, but it cannot guarantee that the data can reach the destination. Because UDP does not need to establish a connection between the client and the server before transmitting the datagram, and there is no timeout and re-transmission mechanism, the transmission speed is very fast.

The differences between TCP and UDP are as follows:

1. the TCP protocol must label the segment when transmitting data segments; UDP protocol does not.

2. Reliable TCP protocol; unreliable UDP protocol.

3. the TCP protocol is connection-oriented, and the UDP protocol is connectionless.

4. High TCP protocol load, using virtual circuits; low UDP protocol load.

5. the sender of the TCP protocol should confirm whether the receiver has received the data segment (three handshakes ).

6. TCP uses window technology and flow control.

34. How to Write a socket?

35. When calling a function, the parameter stack is required. Generally, the order is to press the stack from the rightmost parameter to the left.

36. What types of memory are frequently operated?

Answer: (1) STACK: the compiler automatically allocates and releases the stack, and stores the parameter values and local variable values of the function;

(2) Heap: usually assigned and released by programmers, storing dynamically allocated variables;

(3) Global zone (static zone): The global variables and static variables are stored in this zone, and the initialized and uninitialized sub-zones are opened;

(4) text constant area: the constant string is placed here and automatically released after the program ends;

(5) code area: the binary code of the access function body.

37. Tell the difference between stack and stack.

A: (1) the application method is different. Stacks are automatically allocated and released. On Stacks, programmers apply for and specify the size;

(2) The stack refers to the data structure extended to the low address, with limited size. The stack is extended to the high address and is a non-sequential memory area with relatively large and flexible space;

(3) stacks are allocated and released quickly by the system. stacks are controlled by programmers, which are generally slow and prone to fragmentation;

38. the global variables are placed in the data segment, the internal variable static int count, and the data segment. The internal variable char * P = "AAA", and the position P is on the stack, pointing to the location data segment of the space, internal Variable char
* P = new char; P location heap, pointing to the location data segment of the space

 

39. character array and string comparison: The most obvious difference is that the string will automatically add null characters at the end.

40. concepts related to function pointers (C ++ study notes)

41. How do I access the advantages of using static members in a class?

Answer: advantages:

(1) The static member name is in the scope of the class, so it can avoid conflicts with other class members or global object names;

(2) encapsulation can be implemented. Static members can be private members, but global objects cannot;

(3) Static members are associated with a specific class, which clearly shows the programmer's intent.

The static data member must be in the external definition of the class definition body (exactly once). The static keyword can only be used in the Declaration within the class definition body, and the definition cannot be marked as static. unlike common data members, static members are not initialized through class constructors, nor can they be initialized in class declaration. Instead, they should be initialized during definition. the best way to ensure that objects are exactly defined once is to put the definition of static data members in a file that contains non-inline member function definitions.

The static data member initialization format is:

<Data type> <class name >:< static data member name >=< value>

Static data members of a class can be accessed in two forms:

<Class Object Name>. <static data member name> or <class type name >:< static data member name>

42. static data members and static member functions

Answer: (1) static data member:
Static data members exist independently of any objects of the class. Each static data member is an object associated with the class and is not associated with the object of the class. The static data member (except the const static data member) must be defined externally in the class definition body. Unlike common data members, static members are not initialized through class constructor, but should be initialized during definition.
(2) static member functions:
The static member function does not have this parameter. It can directly access the static member of the class and cannot directly use non-static members. Because static members are not part of any object, they cannot be declared as Const. Static member functions cannot be declared as virtual functions.

43. The static member variable definition is placed in the CPP file and cannot be placed in the initialization list. The const static member can be initialized locally.

 

44. How to reference a defined global variable?

A: You can use the header file reference method or the extern keyword. If you use the header file reference method to reference a global variable declared in the header file, suppose you have written the variable wrong, an error will be reported during compilation. If you reference it using the extern method, if you make the same mistake, no error will be reported during compilation, but an error will be reported during connection.

44. Role of the static keyword.

A: static always changes the storage form of variables or objects to static storage, and the connection mode to internal connections. For local variables (which are already internal connections), it only changes the storage mode; for a global variable (which is already in static storage), it only changes its connection type.

45. nequest Theorem

46. Shannon theorem

47. Does the virtual function table in the polymorphism class be created during compile-time or run-time?

Answer: The virtual function table was created during the compilation period. Each virtual function is organized into an array of virtual function entry addresses. The hidden Member of the object-virtual function table pointer is initialized at runtime-that is, when the constructor is called, which is the key to implementing polymorphism.

48. If a parent class writes a virtual function, can the sub-class overwrite its function without adding virtual?

Is there a function of the parent class or a private variable of the parent class in the subclass space? (Huawei pen exam)

Answer: as long as the base class has declared the virtue keyword when defining the member function, when the derived class is implemented, the virtue keyword can be added or not, without affecting the implementation of polymorphism. All variables of the parent class (except static) exist in the space of the Child class ).

49. sprintf, strcpy, and memcpy functions can be used to copy strings. What are the differences between these functions?

Which one do you like to use? Why?

Answer: The difference between these functions is that they implement different functions and operate on different objects.

(1) The strcpy function operates on a string to copy the source string to the target string.

(2) sprintf function operation objects are not limited to strings: although the target object is a string, the source object can be a string or any basic type of data. This function is mainly used to convert (string or basic data type) to a string. If the source object is a string and the % s format character is specified, you can also copy the string.

(3) The memcpy function, as its name implies, is a memory copy function that copies the content of one memory block to another. The memory block is determined by its first address and length. The entity object that appears in the program, no matter what type, is expressed as occupying a place (a memory interval or block) in the memory ). Therefore, memcpy's operation object is not limited to a certain type of data, or can be applied to any data type, as long as it can provide the initial address and Memory Length of the object, and the object can be operable. Given the features of long copies such as memcpy functions and the physical meaning of data types, memcpy functions are generally limited to copying data of the same type or between objects, of course, it also includes copying strings and basic data types.

For string copying, the above three functions can be used, but their implementation efficiency and ease of use are different:

• Strcpy is undoubtedly the most appropriate choice: High Efficiency and convenient calls.

• Sprintf requires additional format characters and format conversion, which is troublesome and inefficient.

• Although memcpy is efficient, it requires an additional copy memory length parameter, which is error-prone and inconvenient to use. If the length is too large (the optimal length is the source String Length + 1 ), it will also bring about a reduction in performance. In fact, the strcpy function is generally implemented internally by calling the memcpy function or using the Assembly directly to achieve efficient purposes. Therefore, using memcpy and strcpy to copy strings should have no major performance difference.

For non-string data replication, strcpy and snprintf are generally powerless, but there is no impact on memcpy. However, for basic data types, although memcpy can be used for copying, since the value assignment operator can be used to conveniently and efficiently copy data of the same or compatible type, therefore, memcpy is rarely used in this case. Memcpy is used to copy the structure or array (usually internal). Its purpose is to be efficient, convenient to use, or even both.

50. The memory of the application at runtime includes the code zone and data zone. What is the data zone?

A: The memory space of a process can be logically divided into three parts: Code zone, static data zone, and dynamic data zone.

The Dynamic Data zone is generally a "stack ". Stack is a linear structure, and stack is a chain structure. Each thread of a process has a private "stack ".

Global and static variables are distributed in the static data area, and local variables are distributed in the dynamic data area, that is, the stack. The program accesses local variables through the base address and offset of the stack.

51. Which of the following methods can be used to transmit the values of C ++ functions?

A: There are three transfer modes: value transfer, pointer transfer, and reference transfer.

52. Is all the actions in C ++ caused by main? If not, give an example.

For example, the initialization of global variables is not caused by the main function.

Example: Class {};

A A; // The constructor of A is limited to execution.

Int main (){}

53. Which of the following are equivalent?

Int B;

A const int * A = & B;

B const * int A = & B;

C const int * const A = & B;

D int const * const A = & B;

54. Does the inline function perform parameter type check during compilation?

A: inline functions are used to check the parameter type, which is an advantage of inline functions over macros.

55. What is the difference between global variables and local variables? How to implement it? How does the operating system and compiler know?

(1) different lifecycles:

Global variables are created and created with the main program and destroyed with the destruction of the main program.

The local variable exists inside the local function, or even the local cyclic body, so the exit does not exist; the memory is in

Allocated in global data Zone

(2) Different usage methods: each part of the global variable program can be used after declaration; local variables can only be used locally and allocated to the stack.

The operating system and compiler are aware of the location of memory allocation. global variables are allocated in the global data segment and loaded when the program starts running. Local variables are allocated to the stack.

56. There are four people, A, B, C, and D, who want to have a bridge at night. It takes 1, 2, 5, and 10 minutes for them to pass through the bridge. They only have one flashlight and at most two people can bridge the bridge together. How can I arrange for the four to cross the bridge within 17 minutes?

Solution: the key is that two people with the longest time must cross the bridge at the same time.

The first time: A (1) and B (2) Bridge, A (1) return cost: 1 + 2

The second time: C (5) and D (10) Bridge, B (2) returns cost: 10 + 2

The third time A (1) and B (2) bridge cost: 2

Total time cost: (1 + 2) + (10 + 2) + 2 = 17 minutes

57.What is the difference between static global variables and common global variables? What is the difference between static local variables and common local variables? What is the difference between a static function and a common function?

A: What is the difference between static global variables and normal global variables? STATIC global variables are made only once to prevent being referenced in other file units;

Differences between static local variables and common local variables: static local variables are initialized only once, and the next time is based on the previous result value;

Difference between a static function and a common function: a static function has only one copy in the memory, and a normal function maintains one copy in each call.

58. Local variables of the program exist in (stack), global variables exist in (static zone), and dynamic application data exist in (HEAP.

 

59. What implementation is applied to a frequently used short function in C language and in C ++?

C is defined by macro, and C ++ is defined by inline.

60. there are 1, 2 ,.... an unordered Array up to N is used to calculate the sorting algorithm. The time complexity is O (n), the space complexity is O (1), and exchange is used, and only two numbers can be exchanged at a time.

# Include <iostream. h>

Using namespace STD;

Int main (){

Int A [] = };

Int Len = sizeof (a)/sizeof (INT );

Int temp;

For (INT I = 0; I <Len ;)

{

Temp = A [A [I]-1];

A [A [I]-1] = A [I];

A [I] = temp;

If (A [I] = I + 1)

I ++;

}

For (Int J = 0; j <Len; j ++)

Cout <A [J] <",";

Return 0;

}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.