C + + face question Collection

Source: Internet
Author: User
Tags class definition message queue sprintf

1. Why do I add extern "C" when I call a function compiled by the C compiler in a C + + program?
A: First, extern is a keyword that indicates the scope of functions and global variables in the C + + language, which tells the compiler that its declared functions and variables can be used in this module or in other modules.
Typically, the function and global variables that this module provides to other modules in the header file of the module are declared with the keyword extern. extern "C" is a connection declaration (linkage declaration), and the variables and functions modified by extern "C" are compiled and concatenated in C language. As an object-oriented language, C + + supports function overloading, whereas programming language C is not supported. Functions are compiled in C + + with different names in the symbol library than in the C language. For example, suppose a function is prototyped as: void foo (int x, int y), the function is compiled by the C compiler in the symbol library with the name _foo, and the C + + compiler produces names like _foo_int_int. Such a name includes the function name, the number of function parameters, and the type information, which is the mechanism by which C + + implements the function overloading.
Therefore, it is possible to summarize the real purpose of the extern "C" statement in one sentence: solve the name matching problem, and realize the mixed programming between C + + and C.
2. What is the role of IFNDEF/DEFINE/ENDIF in the header file?
A: This is a C + + precompiled header file protector, which ensures that even if a file is included more than once, the header file is defined only once.
3. What is the difference between #include<file.h> and # include "File.h"?
A: The former is looking for and referencing file.h from the standard library path, while the latter is searching from the current work path and referencing file.h.
4. Evaluate the features of the C + +
A: C language is a structured language, process-oriented, based on algorithms and data structures, considering how to get output from input through a process or function;
C + + is Object-oriented, based on class, object and inheritance, the consideration is how to construct an object model, so that the model can fit with the corresponding problem, by acquiring the state information of the object to get output or implementation process control.
5. What is the use of const?
A: in C + +, (1) You can define const constants, (2) The return value and formal parameters of the modifier function;
In C + +, you can also modify the definition body of a function to define a const member function for a class. Const-Modified things are protected against accidental changes and improve the robustness of the program.
6. What is the difference between const and # define?
A: (1) Both const and # define constants can be defined, but the const uses a wider range.
(2) const constants have data types, and macro constants do not have data types. The compiler can perform type safety checks on the former. Instead of only character substitution, there is no type safety check, and the substitution of characters can produce unexpected errors.
(3) Some integrated debugging tools can debug const constants, but cannot debug macro constants.
7. About the sizeof summary.
A: sizeof calculates the amount of memory allocated in the stack.
(1) sizeof does not calculate static variables to occupy memory;
(2) The size of the pointer must be 4 bytes, regardless of the type of pointer;
(3) Char is 1 bytes, int is 4 bytes, short int accounts for 2 bytes
long int is 4 bytes, float is 4 bytes, double is 48 bytes, string is 4 bytes
An empty class takes up 1 bytes, a single inherited empty class occupies 1 bytes, and virtual inheritance involves a virtual pointer so it accounts for 4 bytes
(4) The length of the array:
If the array length is specified, the number of elements is not seen, total bytes = array length *sizeof (element type)
If no length is specified, it is determined by the actual element number class
Ps: If you have a character array, you should consider the null character at the end.

Http://hovertree.com/h/bjaf/hg4nhf1w.htm
(5) Length of the structure object
By default, in order to facilitate access to and management of elements in the structure, when the structure body element length is less than the number of processor bits, the structure of the longest data element in the body of the length of the alignment unit, that is, its integer times. If the element length in the structure is greater than the number of processor digits, it is aligned in the number of processor digits.
(6) unsigned affects only the highest bit meaning, the data length does not change, so sizeof (unsigned int) =4
(7) A custom type of sizeof takes a value equal to its type prototype take sizeof
(8) Use sizeof for the function, which will be replaced by the type of the return value of the function during the compilation phase.
(9) After sizeof, if the type name must be parentheses, if the variable name can be without parentheses, this is because sizeof is an operator
(10) When a struct type or variable is used, sizeof returns the actual size. When a static array is used to return the full size of an array, sizeof cannot return the dimensions of a dynamic array or an outer array
8. What is the difference between sizeof and strlen?
Answer: (1) sizeof's return value type is size_t (unsigned int);
(2) sizeof is an operator, and strlen is a function;
(3) sizeof can use the type parameter, its parameters can be any type or variable, function, and strlen can only use char* to do the parameters, and must be "" to end;
(4) The array as the parameters of sizeof will not degenerate into a pointer, and passed to Strlen is a degenerate pointer;
(5) Sizeo is a compile-time constant, and strlen is calculated at run time, and is the number of characters in the string rather than the memory size;
9. What is the difference between a pointer and a reference?
A: Pointers and references provide the ability to manipulate objects indirectly.
(1) The pointer definition can be uninitialized, and the reference is initialized at the time of definition, and an object binding, and once bound, as long as the reference exists, it will remain and the object's binding;
(2) Differences in assignment behavior: pointer assignment is to re-point the pointer to another object, while the reference assignment is to modify the object itself;
(3) There is a type conversion between pointers, whereas a reference to both a const reference and a non-const application, a non-const reference can only be bound to an object of the same type, a const reference may be bound to an object of a different but related type, or an rvalue
10. What is the difference between an array and a pointer?
A: (1) The array is either created in the global data area or created on the stack, and the pointer can point to any type of memory block at any time;
(2) Changes in the content of the difference:
Char a[] = "Hello";
A[0] = ' X ';
Char *p = "World"; Note P points to the constant string
P[0] = ' X '; The compiler cannot find the error, run-time error
(3) Use the operator sizeof to calculate the capacity (in bytes) of the array. sizeof (p), p is the pointer to the number of bytes of a pointer variable, not the memory capacity referred to by P. The c++/c language has no way of knowing the memory capacity that the pointer refers to, unless you remember it when you request memory. Note that when an array is passed as an argument to a function, the array is automatically degraded to a pointer of the same type.
11. What is the difference between a null pointer and a dangling pointer?
A: A null pointer is a pointer that is assigned a null value, and a pointer to a dynamically allocated object will produce a dangling pointer.
(1) The null pointer can be deleted multiple times, and the pendant pointer is removed again when the program becomes very unstable;
(2) It is illegal to use a null pointer and a dangling pointer, and it can cause a program to crash if the pointer is a null pointer, although it is also a crash, but is a predictable crash compared to dangling pointers.
There are malloc/free in 12.c++, why are there new/delete?
A: Malloc/free is a C + + standard library function, and New/delete is a C + + operator. They can all be used to dynamically request and free memory.
For built-in type data, there is little difference between the two. When malloc applies for memory, it has to set the number of bytes allocated in memory, and it will not initialize; The new application has default initialization and can specify initialization;
For objects of class type, Malloc/free cannot satisfy the requirements. When the object is created, the constructor is automatically executed, and the destructor is called before it dies. Because Malloc/free is a library function and not an operator, the task of executing constructors and destructors cannot be imposed on it without compiler control, so C + + needs to be new/delete.
13. What is a smart pointer?
A: When there are pointer members in a class, there are generally two ways to manage pointer members: One is managed by a value type, each class object retains a copy of the object pointed to by the pointer, and a more elegant way is to use a smart pointer to share the object that the pointer points to.
A common implementation technique for smart pointers is to use reference counting. The smart pointer class relates a counter to the object that the class points to, and the reference count 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, and when the object is created as a copy of another object, the copy constructor copies the pointer and increments the corresponding reference count; When an object is assigned, the assignment operator reduces the reference count of the object referred to by the left operand, if the reference count is reduced Delete the object) and increase the reference count of the object referred to by the right operand; when the destructor is called, 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 of object-oriented technology and what are the three basic features?
A: Basic concepts: Class, Object, inheritance, basic features: encapsulation, inheritance, polymorphism.
Encapsulation: Combining low-level elements to form new, higher-entity technologies;
Inheritance: There are three implementations of generalized inheritance: implementation of inheritance, visual inheritance, interface inheritance.
Polymorphic: A pointer to the parent class type is allowed to assign a pointer to the child class type
What member functions does the 15.c++ empty class default to?
Answer: Default constructor, destructor, copy constructor, assignment function
16. Which member variable can be shared between instances of a class?
Answer: Static member variable
17. In the inheritance hierarchy, why is the base class destructor a virtual function?
A: The compiler always calls the class member function according to the type. However, a pointer to a derived class can be safely converted to a pointer to a base class. When you delete a pointer to a base class, C + +, regardless of whether the pointer points to a base class object or a derived class object, invokes the base class's destructor instead of the derived class. If you rely on the code of the destructor of the derived class to free resources without overloading the destructor, there is a resource leak.
18. Why can't a constructor be a virtual function?
A: Virtual functions take a method of virtual invocation. A call is a mechanism that can work in situations where there is only a partial amount of information. If you create an object, you need to know the exact type of the object, so the constructor cannot be a virtual function.
19. If the virtual function is valid, then why not set all functions as virtual functions?
Answer: No. First, virtual functions have a cost, because each virtual function of the object to maintain a virtual function table, so when the use of virtual functions will incur a certain amount of system overhead, which is not necessary.
20. Constructors can be inline functions
21. What is Polymorphic? What is the role of polymorphism?
A: Polymorphism is a pointer or reference to a base class type that points to an object of a derived type. Polymorphism is realized by virtual function mechanism.
The role of polymorphism is interface reuse.
22. What is the difference between overloading and covering?
A: Virtual functions are functions that the base class wants derived classes to redefine, and the practice of redefining the base class virtual functions by derived classes is called overwriting;
overloading allows multiple functions with the same name to exist in the same scope, which have different parameter tables. The concept of overloading is not object-oriented, and the compiler modifies the names of functions of the same name based on the different formal parameter lists of functions, and then the functions of the same name become different functions.
The determination of overloads is determined at compile time, is static, and virtual functions are dynamically determined at run time.
23. Public inheritance, protected inheritance, private inheritance
A: (1) When the public inherits, the derived class object can access the public member in the base class, and the member function of the derived class can access the public and protected members in the base class;
(2) When the private inheritance, the members of the base class can only be accessed by the members of the directly derived class, and can no longer inherit;
(3) When protected inheritance, the members of the base class are also accessed only by members of the directly derived class and cannot be inherited further down.
24. A member of the public inheritance base class protected can be accessed through a derived class object but cannot be modified.
25. What are the types of cases that can only be initialized with constructors and cannot be initialized with an assignment?
A: const member, reference member
26. What is a virtual pointer?
A: Virtual pointers or virtual function pointers are implementation details of virtual functions. Each object with a virtual function has a virtual pointer to the virtual function table for that class.
27.c++ How do I prevent a class from being instantiated? When do you generally declare a constructor as private?
Answer: (1) Define the class as an abstract base class or declare the constructor as private;
(2) Do not allow class objects to be created outside the class, only objects can be created inside the class
What does the 28.main function do before it executes? Can you execute code after execution?
A: (1) The constructor of the global object is executed before the main function;
(2) Yes, you can register a function with _onexit and it will execute after main;
If you need to add a section of code that executes after main exits, you can use the atexit () function to register a function.
Grammar:
#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.");
}
Results:
This is executed first.
This is executed next.
29. Describe the difference between a process and a thread?
A: (1) The process is the execution of the program, the thread is the execution unit in the process;
(2) The process is independent, which manifests in the memory space, the context environment, the thread runs in the process;
(3) Generally speaking, the process cannot break through the process boundary to access the storage space in other processes, while the same process produces the thread to share the memory space;
(4) Two segments of code in the same process cannot be executed at the same time unless multithreading is introduced.
30. How do I communicate between processes?
Answer: Signal, Semaphore, message queue, shared memory
31. In the network programming involves the concurrent server, uses the multi-process and the multithreading difference?
A: (1) The thread execution cost is small, but it is not conducive to resource management and protection; In contrast, processes can move across machines.
(2) Multiple processes each process has its own memory space, and multi-threaded shared memory space;
(3) The thread produces fast, fast communication between threads, fast switching;
(4) The resource utilization ratio of thread is better;
(5) A synchronization mechanism is required for threads to use public variables or resources.
32. Say the whole process of the TCP 3 handshake and 4 waves.
What is the difference between 33.TCP and UDP.
For:
The tcp--Transmission Control Protocol provides a connection-oriented, 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 the data can be transferred. TCP provides time-out re-send, discard duplicate data, test data, flow control and other functions to ensure that data can be transmitted from one end to the other.
udp--User Datagram Protocol is a simple datagram-oriented transport layer protocol. UDP does not provide reliability, it simply sends the application to the IP layer's datagram, but does not guarantee that it will reach its destination. Because UDP does not have to establish a connection between the client and the server before transmitting the datagram, and there is no mechanism such as time-out retransmission, the transmission speed is very fast.
Some of the characteristics of the TCP protocol and the UDP protocol differ as follows:
The 1.TCP protocol assigns a segment designator to the data segment, which is not required by the UDP protocol.
2.TCP protocol is reliable, UDP protocol is unreliable.
The 3.TCP protocol is connection-oriented, and the UDP protocol is non-connected.
4.TCP protocol with high load, virtual circuit, UDP protocol low load.
The sender of the 5.TCP protocol verifies that the receiving party receives the data segment (3 handshake Protocol).
The 6.TCP Protocol uses window technology and flow control.
34. How do I write sockets?
35. The function is called when the parameter stack, in general, the order is from the rightmost parameter to the left side of the stack.
36. What types of memory do you often have to work with?
A: (1) Stack area: Automatically allocated and released by the compiler, storing the function parameter value, local variable value, etc.;
(2) Heap: Generally by the programmer allocates and releases, stores the dynamic allocation variable;
(3) Global zone (Static zone): Global variables and static variables are stored in this block, initialized and uninitialized points open;
(4) Literal constant area: the constant string is placed here, the program ends automatically released;
(5) Program code area: The binary code of the input function body.
37. Please tell me the difference between heap and stack.
Answer: (1) The application method is different. The stack is automatically assigned and released, and the programmer himself applies and indicates the size of the heap;
(2) The stack is the data structure to the low address extension, the size is very limited, the heap is to the high address extension, is the discontinuous memory area, the space is relatively large and flexible;
(3) The stack is allocated and released by the system quickly; The heap is controlled by the programmer, generally slower and prone to fragmentation;
38. The global variable is placed in the data segment, the internal variable is static int count, placed in the data segment, the internal variable char *p= "AAA", the position of P on the stack, the position of the space pointing to the data segment, the internal variable char *p=new char;p the location heap, Position data segment of the space pointed to

39. Comparison of character arrays to strings: the most obvious difference is that the string automatically adds a null character at the end.
40. Function pointers Related concepts (C + + learning notes)
41. How does a class use the advantages of static members and how to access it?
A: Advantages:
(1) The name of the static member is in the scope of the class, so it is possible to avoid conflicts with the names of members or global objects of other classes;
(2) encapsulation can be implemented. A static member can be a private member, while a global object may not;
(3) A static member is associated with a particular class, which clearly shows the programmer's intentions.
Static data members must be defined outside the class definition body (exactly once), the static keyword can only be used in declarations within the class definition body, and definitions cannot be marked as static. Unlike ordinary data members, static members are not initialized by class constructors or initialized in the declaration of a class, but should be initialized when defined. The best way to ensure that an object is defined exactly once is to place the definition of a static data member in a file containing the definition of a class non-inline member function.
The static data member is initialized in the following format:
Data type >< class name >::< static data member name >=< value
The static data members of a class are accessed in two ways:
Class object name >.< static data member name or class type name >::< static data member name
A. Static data member and static member function
Answer: (1) static data member:
Static data members exist independent of any object of the class, and each static data member is an object associated with the class and is not associated with an object of that class. static data members (except const static data members) must be defined outside the body of the class definition. Unlike normal data members, static members are not initialized by the constructor of the class, but should be initialized at the time of definition.
(2) static member function:
The static member function does not have this parameter, it can directly access the static member of the owning class, and cannot directly use a non-static member. Because the static member is not part of any object, the static member cannot be declared as Const. Also, the static member function cannot be declared as a virtual function.
The 43.static member variable definition is placed in the CPP file and cannot be placed in the initialization list. A Const static member can be initialized in place.

44. How do I refer to a global variable that has already been defined?
A: You can use the method of referring to the header file, you can also use the extern keyword, if you use a reference header file to refer to a global variable declared in the header file, if you write that variable wrong, then the compilation will be error, if you use extern way to reference, assuming you made the same mistake, There will be no error during compilation and an error during connection.
The role of the 44.static keyword.
A: Static always makes the stored form of a variable or object into a static storage, the connection becomes an internal connection, and for a local variable (already internally connected), it only changes its storage mode, and for global variables (which are already statically stored), it only changes its connection type.
45. Nyquist theorem
46. Shannon's theorem
47. is the virtual function table in a polymorphic class compile-time, or is it established when run-time?
Answer: Virtual function tables are built at compile time, and each virtual function is then organized into an array of entry addresses for a virtual function. The hidden member of the object-the virtual function table pointer is initialized at run time-that is, when the constructor is called, which is the key to realizing polymorphism.
48. A parent class writes a virtual function, and if the subclass overrides its function without virtual, it can also implement polymorphism.
In a subclass of space, is there a function of the parent class, or a private variable of the parent class? (Huawei written questions)
Answer: As long as the base class has declared the Virtue keyword when defining a member function, when overridden by a derived class, the Virtue keyword can be added without affecting the implementation of the polymorphic. The subclass has all the variables of the parent class (except static) in the space.
49. Complete string copy can use sprintf, strcpy and memcpy functions, what is the difference between these functions
, which do you like to use and why?
Answer: The difference between these functions is the implementation of functions and the different objects of operation.
(1) The object that the strcpy function operates on is a string that completes the copy function from the source string to the destination string.
(2) The object that the sprintf function operates on is not limited to strings: Although the destination object is a string, the source object can be a string, or it can be any basic type of data. This function is mainly used to implement the conversion function (string or basic data type) to the string. If the source object is a string, and you specify the%s format character, you can also implement the string copy feature.
(3) The memcpy function, as its name implies, is a memory copy that implements the ability to copy the contents of one block of memory to another block of memory. The memory block is determined by its first address and its length. An entity object that appears in a program, regardless of its type, is ultimately represented in memory (a memory interval or block). Therefore, the memcpy object is not limited to a class of data types, or can be applied to any data type, as long as the object can give the start address and memory length information, and the object can be operable. Given the characteristics of the memcpy function and the physical meaning of the data type, the memcpy function is usually limited to copies of the same type of data or objects, including, of course, the copy of the string and the base data type.
For a string copy, the above three functions can be implemented, but its implementation efficiency and ease of use are different:
strcpy is undoubtedly the most suitable choice: high efficiency and easy to invoke.
sprintf to specify format characters and convert them in a format that is cumbersome and inefficient.
memcpy is efficient, but requires additional copies of the memory length of the parameter, error-prone and inconvenient to use, and if the length is specified too large (the optimal length is the source string length + 1), but also bring performance degradation. In fact, strcpy function is generally called in the internal memcpy function or the assembly is directly implemented, in order to achieve efficient purposes. Therefore, there should be no significant difference in performance between using memcpy and strcpy copy strings.
For non-string type of data replication, strcpy and snprintf generally powerless, but to memcpy but no impact. However, for basic data types, although copies can be made with memcpy, because there are assignment operators that can easily and efficiently copy between data of the same or compatible type, the memcpy is rarely used in this case. The advantage of memcpy is to make a copy of the structure or array (usually the internal implementation), which is either efficient, convenient, or even both.
50. The memory of the application at runtime includes the code area and the data area, and which parts are included in the data area?
A: For the memory space of a process, it can be logically divided into 3 parts: code area, static data area and dynamic Data area.
Dynamic Data areas are generally "stacks". A stack is a linear structure, and a heap is a chain structure. Each thread of the process has a private "stack".
Global variables and static variables are allocated in the static data area, and local variables are allocated in the Dynamic Data area, which is the stack. The program accesses local variables through the base address and offset of the stack.
What are the methods of passing values in C + + functions?
A: Three delivery methods are: value passing, pointer passing, and reference passing.

Push: http://www.cnblogs.com/roucheng/p/3456005.html
All the actions in C + + are caused by main ()? If not, please 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 two 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 do parameter type checking at compile time?
Answer: Inline functions do parameter type checking, which is an advantage of inline functions compared to macros.
55. What is the difference between a global variable and a local variable? How did it come true? How does the operating system and the compiler know?
(1) Different life cycle:
Global variables are created and created with the main program and destroyed with the main program destroyed
Local variables exist inside local functions, even local loop bodies, and exits do not exist; in-memory
Assign in global data area
(2) The use of different ways: through the declaration of the various parts of the global variable program can be used; local variables can only be used locally, allocated in the stack area
The operating system and compiler know by the location of the memory allocation, the global variable is assigned to the global data segment and is loaded when the program starts to run. Local variables are allocated inside the stack.
56. Have a, B, C, D four people, to cross a bridge at night. They take 1, 2, 5, 10 minutes, each with only a flashlight, and can only have a maximum of two people crossing the bridge at the same time. Excuse me, how can I arrange for these four people to cross the bridge within 17 minutes?
Solution: The key is that the longest two people 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) return cost:10+2
The third time A (1) and B (2) Bridge Cost:2
Total time Cost: (1+2) + (10+2) +2=17 minutes
What is the difference between a static global variable and a normal global variable? What is the difference between a static local variable and a normal local variable? What is the difference between a static function and a normal function?
A: The static global variable differs from the normal global variable: the static global variable is only initialized once, preventing it from being referenced in other file units;
Static local variable differs from ordinary local variable: Static local variable is initialized only once, next time based on last result value;
The static function differs from the normal function: The static function has only one copy in memory, and the normal function maintains a copy of each call.
58. The local variables of the program exist in (the stack), the global variables exist in the (static zone), the dynamic request data exists in (heap).

59. For a short function that is frequently used, what implementations are applied in C, and what implementations are applied in C + +?
C with macro definition, C + + with inline
60.,.... An unordered array of up to N, a sorting algorithm, and requires a time complexity of O (n), a space complexity O (1), an interchange, and only two numbers can be exchanged at one time.

#include <iostream.h>Usingnamespacestd;intMain () {intA[] = {Ten,6,9,5,2,8,4,7,1,3};intLen =sizeof(a)/sizeof(int);inttemp; for(inti =0; I <Len;) {Temp= A[a[i]-1];a[a[i]-1] =A[i];a[i]=temp;if(A[i] = = i +1) I++;} for(intj =0; J < Len; J + +) cout<<a[j]<<",";return 0;}//by Ho asked Hovertree.com

Transferred from: http://hovertree.com/h/bjaf/cppmianshi.htm

C + + face question Collection

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.