C/C ++ written examination, Interview Questions Summary

Source: Internet
Author: User
Tags ole

C/C ++ written examination, Interview Questions Summary
1. Find the return value of the following function (Microsoft)

Int func (X)
{
Int countx = 0;
While (X)
{
Countx ++;
X = x & (x-1 );
}
Return countx;
}

Assume x = 9999. Answer: 8

Train of Thought: Convert X to a binary system and check the number of contained 1.

2. What is "reference "? What should I pay attention to when declaring and using "reference?

A: A reference is the "alias" (alias) of a target variable. operations on an application are identical to operations on a variable. When declaring a reference, remember to initialize it. After the reference declaration is complete, the target variable name has two names, that is, the original name and reference name of the target, and the reference name cannot be used as the alias of other variable names. Declaring a reference is not a new variable. It only indicates that the reference name is an alias of the target variable name. It is not a data type, so the reference itself does not occupy the storage unit, the system does not allocate storage units to references. You cannot create an array reference.

3. What are the features of using "Reference" as a function parameter?

(1) passing a reference to a function has the same effect as passing a pointer. In this case, the parameter of the called function becomes an actual parameter variable or an alias of the object in the original main function, therefore, the operations on the parameters in the called function are the operations on the corresponding target object (in the main function.

(2) using the reference parameter to pass the function does not generate a copy of the real parameter in the memory, it is directly to operate on the real parameter; while using the general variable to pass the function parameter, when a function call occurs, you need to allocate storage units to the parameters. The parameters are copies of the real variables. if the object is passed, the copy constructor will also be called. Therefore, when the data transmitted by a parameter is large, it is better to use reference than to transmit a parameter using a common variable.

(3) Although using pointers as function parameters can achieve the same effect as using references, in the called function, storage units must be allocated to the parameters, the "* pointer variable name" format must be used repeatedly for calculation, which can easily lead to errors and the program reading is poor. On the other hand, at the call point of the main function, the variable address must be used as the real parameter. References are easier to use and clearer.

4. When do I need to use "regular reference "?

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

Example 1

Int;
Const Int & RA =;
Ra = 1; // Error
A = 1; // correct

Example 2

String Foo ();
Void bar (string & S );

The following expression is invalid:

Bar (FOO ());
Bar ("Hello World ");

The reason is that both the Foo () and "Hello World" strings generate a temporary object. In C ++, these temporary objects are of the const type. Therefore, the above expression tries to convert a const type object to a non-const type, which is invalid.

The referenced parameter should be defined as const if it can be defined as Const.

5. Use "Reference" as the format, benefits, and rules of the function return value type?

Format: type identifier & function name (parameter list and type description) {// function body}

Benefit: do not generate a copy of the returned value in the memory. (Note: For this reason, it is not advisable to return a reference to a local variable. As the survival of the local variable ends, the corresponding reference will also become invalid, resulting in a runtime error!

Note:

(1) References to local variables cannot be returned. For details, refer to item 31 of Objective C ++ [1. The main reason is that local variables will be destroyed after the function returns, so the returned reference becomes a reference of "no finger", and the program enters the unknown state.

(2) You cannot return a reference to the memory allocated by the new function. For details, refer to item 31 of Objective C ++ [1. Although there is no passive destruction of local variables, this situation (returning a reference to the memory allocated by the new function) faces other embarrassing situations. For example, if a reference returned by a function only appears as a temporary variable and is not assigned to an actual variable, the space pointed to by the reference (allocated by new) cannot be released, cause memory leak.

(3) You can return a reference to a class member, but it is best to use Const. This principle can be referred to item 30 of Objective C ++ [1. The main reason is that when an object attribute is associated with a business rule, its value assignment is often related to some other attributes or the state of the object, therefore, it is necessary to encapsulate the value assignment operation in a business rule. If other objects can obtain the non-constant reference (or pointer) of this attribute, a simple value assignment to this attribute will damage the integrity of business rules.

(4) The function of declaring the returned value of stream operator overload as "Reference:

Stream operators <and>, which are often used consecutively, for example, cout <"hello" <Endl; therefore, the return value of these two operators should be a stream reference that still supports these two operators. Other optional solutions include returning a stream object and returning a stream object pointer. However, for a returned Stream object, the program must re-(copy) to construct a new stream object. That is to say, two consecutive <operators are actually for different objects! This is unacceptable. If a stream pointer is returned, the <operator cannot be used consecutively. Therefore, returning a stream object reference is the only choice. This unique choice is critical. It illustrates the importance of reference and is irreplaceable. Maybe this is why the concept is introduced in C ++. Value assignment operator =. This operator can be used continuously like a stream operator, for example, x = J = 10; or (x = 10) = 100; the return value of the value assignment operator must be a left value, so that the value can be assigned. Therefore, it is referenced as the only return value choice of this operator.

Example 3

# I nclude <iostream. h>
Int & put (int n );
Int Vals [10];
Int error =-1;
Void main ()
{
Put (0) = 10; // use the put (0) function value as the left value, equivalent to Vals [0] = 10;
Put (9) = 20; // use the put (9) function value as the left value, which is equivalent to Vals [9] = 20;
Cout <Vals [0];
Cout <Vals [9];
}
Int & put (int n)
{
If (n> = 0 & n <= 9) return Vals [N];
Else {cout <"subscript error"; Return Error ;}
}

(5) among other operators, the reference: +-*/four Arithmetic Operators cannot be returned. They cannot return references. The Objective C ++ [1] item23 discusses this issue in detail. The main reason is that these four operators do not have side effect. Therefore, they must construct an object as the return value. Optional solutions include: returning an object and returning a reference to a local variable, returns the reference of a newly assigned object and a static object reference. According to the preceding three rules that reference the returned value, both the 2nd and 3 schemes are rejected. Static object reference is caused by errors because (a + B) = (C + D) is always true. Therefore, only one object is returned.

6. What is the relationship between "reference" and polymorphism?

References are another method that can produce polymorphism effects except pointers. This means that a base class reference can point to its derived class instance.

Example 4

Class A; Class B: Class A {...}; B; A & ref = B;

7. What is the difference between "reference" and pointer?

After a pointer variable points to an object, it indirectly operates on the variable it points. When pointers are used in a program, the program has poor readability. The reference itself is the alias of the target variable, and the reference operation is the operation of the target variable. In addition, it is the difference between the ref passed to the function and the pointer mentioned above.

8. When do I need to "Reference "?

Stream operators <and>, return values of the value assignment operator =, parameters of the copy constructor, parameters of the value assignment operator =, and references are recommended in other cases.

Above 2-8 reference: http://blog.csdn.net/wfwd/archive/2006/05/30/763551.aspx

9. What is the difference between the structure and the union?
1. the structure and union are composed of multiple members of different data types, but at any time, only one selected member is stored in the Union (all members share an address space ), all members of the structure exist (the storage addresses of different members are different ).
2. assigning values to different members of the Union will be rewritten to other members. The original value of the members does not exist, but the assignment values to different members of the structure do not affect each other.

10. What is the output of the following question about "union?

A)

# I nclude <stdio. h>
Union
{
Int I;
Char X [2];
};

Void main ()
{
A. X [0] = 10;
A. X [1] = 1;
Printf ("% d", A. I );
}
Answer: 266 (low address, high address, memory usage is ox010a)

B)

Main ()
{
Union {/* define a Union */
Int I;
Struct {/* define a structure in the Union */
Char first;
Char second;
} Half;
} Number;
Number. I = 0x4241;/* Union member assignment */
Printf ("% C/N", number. Half. First, mumber. Half. Second );
Number. Half. First = 'a';/* assign values to structure members in the Union */
Number. Half. Second = 'B ';
Printf ("% x/N", number. I );
Getch ();
}
Answer: AB (0x41 corresponds to 'A', which is low; ox42 corresponds to 'B', which is high)

6261 (number. I and number. half share an address space)

11. The strcpy function prototype is known: char * strcpy (char * strdest, const char * strsrc) Where strdest is the destination string and strsrc is the source string. Do not call the string library function of C ++/C. Compile the strcpy function.

Answer:
Char * strcpy (char * strdest, const char * strsrc)
{
If (strdest = NULL | strsrc = NULL)
Return NULL;
If (strdest = strsrc)
Return strdest;
Char * tempptr = strdest;
While (* strdest ++ = * strsrc ++ )! = '/0 ')
;
Return tempptr;
}

12. The string class is defined as follows:

Class string
{
Public:
String (const char * STR = NULL); // common Constructor
String (const string & Another); // copy the constructor
~ String (); // destructor
String & operater = (const string & RHs); // value assignment function
PRIVATE:
Char * m_data; // used to save strings
};

Try to write out the member function implementation of the class.

Answer:

String: string (const char * Str)
{
If (STR = NULL) // If the strlen parameter is null, an exception is thrown.
{
M_data = new char [1];
M_data [0] = '/0 ';
}
Else
{
M_data = new char [strlen (STR) + 1];
Strcpy (m_data, STR );
}

}

String: string (const string & Another)
{
M_data = new char [strlen (another. m_data) + 1];
Strcpy (m_data, other. m_data );
}

String & string: Operator = (const string & RHs)
{
If (this = & RHs)
Return * this;
Delete [] m_data; // Delete the original data with a new memory
M_data = new char [strlen (RHS. m_data) + 1];
Strcpy (m_data, RHS. m_data );
Return * this;
}

String ::~ String ()
{
Delete [] m_data;
}

13. What is the function of ifndef/define/endif in the. h header file?

A: prevent this header file from being repeatedly referenced.

14. # What is the difference between I nclude <file. h> and # I nclude "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.

15. Why should I add the extern "C" to call the function compiled by the C compiler in the C ++ program "?

First, as extern is a keyword in C/C ++ that indicates the range (visibility) of the function and global variable. This keyword tells the compiler, 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. For example, if Module B wants to reference the global variables and functions defined in module A, it only needs to include the header file of module. In this way, when Module B calls a function in module A, although Module B cannot find the function in the compilation phase, no error is reported; it will find this function from the target Code Compiled by module A in the connection phase.

Extern "C" is a linkage declaration. Variables and functions modified by extern "C" are compiled and connected in C language, let's take a look at how C-like functions are compiled in C ++:

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, while the C ++ compiler generates names such as _ foo_int_int (different compilers may generate different names, but all adopt the same mechanism, and the new name is called "mangled name ").

A name such as _ foo_int_int contains the function name, number of function parameters, and type information. c ++ relies on this mechanism to implement function overloading. For example, in C ++, the void Foo (int x, int y) and void Foo (int x, float y) functions generate different symbols, the latter is _ foo_int_float.

Similarly, variables in C ++ support both local variables and class member variables and global variables. The class member variables of the program written by the user may have the same name as the global variables, which are distinguished. In essence, the compiler uses a unique name for the variables in the class when compiling, similar to the function processing. This name is different from the global variable name with the same name in the user program.

Connection method when extern "C" is not added

Suppose in C ++, the header file of module A is as follows:

// Module A header file modulea. h
# Ifndef module_a_h
# Define module_a_h
Int Foo (int x, int y );
# Endif

Reference this function in Module B:

// Module B implements the file moduleb. cpp
# I nclude "modulea. H"
Foo (2, 3 );
  

In fact, in the connection phase, the connector looks for symbols such as _ foo_int_int from the target file modulea. OBJ generated by module!

Compilation and Connection Methods After the extern "C" clause is added

After the extern "C" statement is added, the header file of module A is changed:

// Module A header file modulea. h
# Ifndef module_a_h
# Define module_a_h
Extern "C" int Foo (int x, int y );
# Endif

In Module B's implementation file, Foo (2, 3) is still called. The result is:
(1) When module A compiles and generates the foo target code, it does not perform special processing on its name and uses the C language;

(2) When the connector looks for the Foo (2, 3) call for the target code of Module B, it looks for the unmodified symbol name _ Foo.

If the function in module A declares that foo is of the extern "C" type, and Module B contains the extern int Foo (INT X, int y ), module B cannot find the function in module A, and vice versa.

Therefore, we can summarize the true purpose of the statement "extern" C "in one sentence (the birth of any syntax feature in any language is not random and comes from the needs of the real world. When thinking about a problem, we should not just focus on how the language is made, but also ask why it is doing so and what the motivation is, so that we can better understand many problems ): realize mixed programming of C ++, C and other languages.

Understand the motivation for setting up extern "C" in C ++. Next we will analyze the common usage skills of extern "C:

Usage of extern "C"

(1) To reference functions and variables in C language in C ++, the following processing must be performed when the C Language header file (assumed as cexample. h) is included:

Extern "C"
{
# I nclude "cexample. H"
}

In the header file of the C language, the external function can only be specified as the extern type. The C language does not support the extern "C" declaration. when the c file contains extern "C", a compilation syntax error occurs.

C ++ references the source code of the three files contained in the C function example project as follows:

/* C header file: cexample. H */
# Ifndef c_example_h
# Define c_example_h
Extern int add (int x, int y );
# Endif

/* C language implementation file: cexample. C */
# I nclude "cexample. H"
Int add (int x, int y)
{
Return X + Y;
}

// C ++ implementation file, call Add: cppfile. cpp
Extern "C"
{
# I nclude "cexample. H"
}
Int main (INT argc, char * argv [])
{
Add (2, 3 );
Return 0;
}

If C ++ calls a. dll written in C language, when it includes the header file of. dll or the declared interface function, it should add extern "C "{}.

(2) When referencing functions and variables in C ++ in C, the header file of C ++ needs to add extern "C ", however, you cannot directly reference this header file that declares extern "C" in C. You should only declare the extern "C" function defined in C ++ as the extern type.

C references the source code of the three files contained in the C ++ function example project as follows:

// C ++ header file cppexample. h
# Ifndef cpp_example_h
# Define cpp_example_h
Extern "C" int add (int x, int y );
# Endif

// C ++ implementation file cppexample. cpp
# I nclude "cppexample. H"
Int add (int x, int y)
{
Return X + Y;
}

/* C implementation file cfile. c
/* Compilation errors: # I nclude "cexample. H "*/
Extern int add (int x, int y );
Int main (INT argc, char * argv [])
{
Add (2, 3 );
Return 0;
}

15 for answers to the questions, please refer to the "Deep Exploration of the meaning of extern" C "in C ++" Note:

16. What are the differences between Association, aggregation, and composition?

Involves some concepts in UML: Association refers to the general relationship between two classes. For example, "student" and "teacher" are an association relationship. Aggregation refers to the relationship between has-, is a relatively loose relationship, and the aggregation class does not need to be responsible for the aggregated class, as shown in, using an empty diamond to represent the aggregation relationship:

 

From the implementation perspective, aggregation can be expressed:

Class A {...} Class B {A * ;.....}

The combination represents the relationship between ins-A, and the correlation is stronger than aggregation: The combination class has the same lifecycle as the composite class. The combination class is responsible for the combination class, and the solid diamond is used to represent the combination relationship:

 

The implementation form is:

Class A {...} Class B {;...}

Reference: http://blog.csdn.net/wfwd/archive/2006/05/30/763753.aspx

Http://blog.csdn.net/wfwd/archive/2006/05/30/763760.aspx

17. What are the three basic features of object-oriented architecture?

1. encapsulation: Abstract Objective objects into classes. Each class implements protection (private, protected, public) on its own data and methods)

2. inheritance: generalized inheritance has three implementation forms: Implementation inheritance (the ability to use the attributes and methods of the base class without additional encoding) visual inheritance (child forms use the appearance and implementation code of the parent form) and interface inheritance (only properties and methods are used to implement sub-classes ). The first two methods (class inheritance) and the last one (Object combination => interface inheritance and pure virtual functions) constitute two methods of function reuse.

3. polymorphism: a technology that sets a parent object to be equal to one or more other sub-objects, the parent object can operate in different ways based on the features of the sub-objects assigned to it. To put it simply, you can assign a pointer of the subclass type to a pointer of the parent class.

18. What is the difference between overload and overried?

Common Questions. In terms of definition:

Overload: multiple functions with the same name are allowed, and the parameter tables of these functions are different (maybe the number of parameters is different, maybe the parameter types are different, or both are different ).

Rewrite: it refers to the method for the subclass to redefine the complex class virtual function.

In terms of implementation principle:

Overload: 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 (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 ;. The modified function names of the compiler may be: int_func and str_func. The call to these two functions is determined between compilers and is static. That is to say, their addresses are bound during compilation (early binding). Therefore, overloading is irrelevant to polymorphism!

Rewriting: It is really related to polymorphism. When the subclass redefined the virtual function of the parent class, the parent class pointer dynamically calls the function of the subclass according to the different subclass pointer assigned to it, such a function call cannot be determined during compilation (the virtual function address of the called subclass cannot be provided ). Therefore, such function addresses are bound at runtime (late binding ).

19. What is the role of polymorphism?

There are two main types: 1. hide implementation details to modularize the code. Expand the code module to reuse the code. 2. interface reuse: This ensures that a class is called correctly when using a certain attribute of an instance of any class in the family during class inheritance and derivation.

20. What are the differences between ADO and ado.net?

Apart from the basic similarities that allow applications to process data stored in DBMS, there is not much in common between the two. However, ADO uses ole db interfaces and is based on Microsoft's COM technology, while ADO. Net has its own ADO. net interface and is based on Microsoft's. NET architecture. As we all know, the. NET system is different from the com system, and the ADO. net interface is completely different from the ADO and ole db interfaces. That is to say, ADO. NET and ADO are two data access methods. Ado.net provides support for XML.

21. What are the relationships and differences between New Delete and malloc free?
Answer: all are dynamic memory operations on heap. To use the malloc function, you must specify the number of bytes allocated by the memory and Cannot initialize the object. New automatically calls the object constructor. Delete calls the destructor of the object, but free does not call the destructor of the object.

22. # define double (x) x + X, I = 5 * double (5); what is I?
Answer: I is 30.

23. In which situations can I use the intialization list instead of the assignment?

Answer: when the class contains const and reference member variables, the base class constructors need to initialize the table.

24. Is C ++ type safe?
Answer: No. Two different types of pointers can be forcibly converted (reinterpret cast ). C # is type-safe.

25. What code will be executed before the main function is executed?
Answer: The constructor of the global object is executed before the main function.

26. describes the memory allocation methods and their differences?
1) distributed from the static storage area. The program has been allocated when it is compiled, and the program exists throughout the entire runtime. For example, global variables and static variables.
2) create a stack. When a function is executed, the storage units of local variables in the function can be created on the stack. When the function is executed, these storage units are automatically released. Stack memory allocation operations are embedded in the processor's instruction set.
3) distributed from the stack, also known as dynamic memory allocation. When the program runs, it uses malloc or new to apply for any amount of memory. The programmer is responsible for releasing the memory with free or delete. The lifetime of the dynamic memory is determined by the programmer. It is very flexible to use, but the problem is also the most.

27. Differences between struct and class

Answer: struct members are public by default, while Class Members are private by default. Struct and class are quite functional in other aspects.

Emotionally, most developers feel that classes and structures are very different. It seems that the structure is just like a bunch of open memory spaces that lack encapsulation and functionality, and the class is like a living and reliable social member. It has smart services, it has a strong encapsulation barrier and a well-defined interface. Since most people think so, there are only a few methods in your class and public data (this kind of thing exists in a well-designed system !) You should use the struct keyword. Otherwise, you should use the class keyword.

28. When a Class A does not have any member variables and member functions, what is the value of sizeof (a)? If it is not zero, explain why the compiler didn't make it zero. (Autodesk)
Answer: it must not be zero. For example, if it is zero, declare an array of Class A [10] objects, and each object occupies zero space. In this case, a [0] cannot be distinguished. A [1]… .

29. In the 8086 assembly, how is the logical address and physical address converted? (Intel)
Answer: The address provided by the general register is the intra-range offset address. The corresponding segment register address * 10 h + the intra-range address in the General Register gets the address to be accessed.

30. How do I compare the four types of conversion methods in C ++?

For details, refer to the differences and Applications of role, dynamic_cast and reinterpret_cast.

31. Write the comparison statements of Boolean, Int, float, and pointer type variables A and zero respectively.
Answer:
Bool: If (! A) or if ()
INT: if (a = 0)
Float: const expressions exp = 0.000001
If (A <exp & A>-exp)
Pointer: if (! = NULL) or if (a = NULL)

 

32. What are the advantages of const compared with # define?
Answer: 1) 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.
2) some integrated debugging tools can debug const constants, but cannot debug macro constants.
 

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.