Interview 2 (Summary of C/C ++ questions (Microsoft ))

Source: Internet
Author: User

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. The operations on a reference are identical to those 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 with an actual variable, the space pointed to by this 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://hi.baidu.com/zhanghaooy/blog/item/ff801c3f8da77bca7d1e7120.html

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: # include <FILENAME. h> references the header file of the standard library (search from the standard library directory) and searches for it directly from the library.
# Include "filename. H" refers to the header file of the non-standard library (search from the user's working directory) first in the current location, if not found in the slave library to find

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, when the compiler is compiling, it is similar to the function processing, and it also takes a unique name for the variables in the class, 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 {;...}

Prevent the header file from being repeatedly referenced. If the header file is repeatedly referenced, the file content has different consequences, such as repeated definitions.

For example, it can be used to prevent multiple headers from containing the same header file.
# Ifndef salesitem_h
# Define salesitem_h
# Endif
# Ifndef indicates whether to check whether the presalesitem_h processor variable is undefined. If not
,
Then all subsequent instructions are processed until they appear # endif

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.