C + + common face test 30 road

Source: Internet
Author: User

1.new, delete, malloc, free relationships

Delete invokes the object's destructor, and new corresponds to free only frees memory, and new calls the constructor. malloc and free are standard library functions for c++/c languages, and new/delete are operators of C + +. They can all be used to request dynamic memory and free memory. For objects of non-intrinsic data types, light Maloc/free cannot meet the requirements of dynamic objects. Objects are automatically executed when they are created, and the object executes the destructor automatically 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 malloc/free, not within the control of the compiler. Therefore, the C + + language requires an operator new that can perform dynamic memory allocation and initialization, and an operator delete that can perform cleanup and deallocation work. Note New/delete is not a library function.

2.delete differs from delete []

Delete will only call a destructor, and delete[] will call the destructor for each member. In more effective C + +, there is a more detailed explanation: "When the delete operator is used in an array, it calls the destructor for each array element and then calls operator delete to free up memory." "Delete with new, delete [] and new [] Package

Memtest *mtest1=new memtest[10];

Memtest *mtest2=new memtest;

int *pint1=new int [10];

int *pint2=new int;

Delete[]pint1; -

Delete[]pint2; -

delete[]mtest1;//-3-

delete[]mtest2;//-4-

Error at-point.

This means that the delete and delete[] functions are the same for the built-in simple data types. Delete and delete[] are not interoperable for custom complex data types. Delete[] Delete an array, delete deletes a pointer. Simply put, the memory allocated with new is deleted with delete; memory allocated with new[] is deleted with delete[]. Delete[] will invoke the destructor of the array element. There is no destructor for internal data types, so the problem is not very large. If you use delete without parentheses, delete will assume that it is pointing to a single object, otherwise it will assume that it is pointing to an array.

What are the properties of 3.c++ (object-oriented characteristics)

Encapsulation, inheritance, and polymorphism.

4. Do you want to call the destructor of the parent class when the subclass is destructor?

The order of destructor calls is the destructor of the derived class first, that is, the information of the derived class is destroyed when the destructor of the base class is called. When you define an object, call the constructor of the base class, and then call the constructor of the derived class; The destructor of the derived class is called first, and then the destructor of the base class is called.

5. Polymorphism, virtual function, pure virtual function

Polymorphic: Different actions are generated when different objects receive the same message. The polymorphism of C + + is embodied in two aspects of running and compiling: The polymorphism is embodied by inheritance and virtual function when the program runs;

Polymorphism is manifested in the overloading of functions and operators at the time of program compiling;

virtual function: A member function that is prefixed with the keyword virtual in the base class. It provides an interface interface. Allows you to redefine the virtual function of a base class in a derived class.

Pure virtual function: The name of a function is reserved for its derived class in the base class so that the derived class can define it as needed. As an interface, the existence of a pure virtual function does not have functions, and generally cannot be called directly.

A pure virtual function inherited from a base class, which is still a virtual function in a derived class. If there is at least one pure virtual function in a class, then this class is called an abstract class.

Abstract classes include not only pure virtual functions, but also virtual functions. An abstract class must be used as a base class for deriving other classes, and cannot be used to create object instances directly. However, you can still use pointers to abstract classes to support run-time polymorphism.

6. 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

Idea: Convert x into 2, and see the number of 1.

7. What is a "citation"? What are the issues to be aware of and use of "references"?

A: A reference is an alias for a target variable, and the action on the app is exactly the same as the direct action on the variable. When declaring a reference, remember to initialize it. When the reference declaration is complete, the target variable name is equal to two names, that is, the target name and reference name, and the reference name cannot be used as an alias for the other variable names. Declaring a reference is not a new definition of a variable, it simply means that the reference name is an alias of the target variable name, it is not a data type in itself, so the reference itself does not account for the storage unit, and the system does not assign a storage unit to the reference. You cannot create a reference to an array.

8. What are the characteristics of "reference" as a function parameter?

(1) The effect of passing a reference to a function is the same as passing a pointer. At this point, the parameter of the function is used as the real parametric or an alias of the object in the original central melody function, so the operation of the parameter variable in the function is the operation of its corresponding target object (in the central Melody function).

(2) using the parameters of the reference transfer function, in memory does not produce a copy of the argument, it is directly to the actual parameter operation, while using the general variable transfer function parameters, when a function call, you need to assign a storage unit to the parameter, the parameter variable is the copy of the argument variable; Therefore, when the parameter passes the data is large, uses the reference to pass the parameter with the general variable efficiency and occupies the space to be good.

(3) The use of pointers as parameters of the function, although also can achieve with the use of reference, but in the function of the parameter allocation of the same storage unit, and the need to re-use "* pointer variable name" in the form of operations, which is prone to error and poor program reading; On the other hand, at the call point of the keynote function You must use the address of the variable as the argument. And references are easier to use and clearer.

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

If you need to use references to improve the efficiency of the program, but also to protect the data passed to the function is not changed in the function, you should use a constant reference. Common Reference declaration method: Const type identifier & reference name = target variable name;

Example 1

int A;

const INT &ra=a;

Ra=1; Error

A=1; That's right

Example 2

string foo ();

void Bar (string & S);

Then the following expression will be illegal:

Bar (foo ());

Bar ("Hello World");

The reason is that both the Foo () and the "Hello World" strings produce a temporary object, whereas in C + + These temporary objects are const types. So the expression above is an attempt to convert an object of a const type to a non-const type, which is illegal. Reference parameters should be defined as const when they can be defined as const.

10. What are the formats, benefits, and rules that you need to follow to return a value type as a function?

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

Benefit: No copy of the returned value is generated in memory; (Note: It is for this reason that it is undesirable to return a reference to a local variable.) Because with the end of the local variable's lifetime, the corresponding reference will also be invalidated, resulting in runtime error!

Precautions:

(1) A reference to a local variable cannot be returned. This article can refer to effective c++[1] Item 31. The main reason is that the local variable is destroyed after the function returns, so the returned reference becomes a "no" reference, and the program goes into an unknown state.

(2) You cannot return a reference to the memory that is allocated inside the function. This article can refer to effective c++[1] Item 31. Although there is no passive destruction of local variables, there are other embarrassing situations in which the case (a reference to new allocation of memory within the function) is returned. For example, a reference returned by a function is only present as a temporary variable, not given an actual variable, and the space pointed to by the reference (allocated by new) cannot be freed, resulting in memory leak.

(3) A reference to a class member can be returned, but preferably a const. This principle can be referenced by effective C++[1] Item 30. The main reason is that when an object's property is associated with a business rule, its assignment is often related to the state of some other attribute or object, so it is necessary to encapsulate the assignment in a business rule. If other objects can get a very good reference (or pointer) to the property, the simple assignment of that property will break the integrity of the business rules.

(4) The function of the return value of the stream operator overload declaration is "reference":

Stream operators << and >>, these two operators often want to be used continuously, for example: cout << "Hello" << Endl; Therefore, the return value of these two operators should be a stream reference that still supports both operators. Alternative options include returning a stream object and returning a pointer to a stream object. But for a stream object to be returned, the program must recreate (copy) a new stream object, that is to say, two consecutive << operators are actually for different objects! It's not acceptable to anyone. The << operator cannot be used consecutively for returning a stream pointer. Therefore, returning a Stream object reference is the only option. This unique choice is key, it shows the importance of the reference and the irreplaceable, perhaps this is the introduction of the concept of reference in the C + + language is the reason for it.

Assignment operator =. This operation, like the Fuchang operator, can be used consecutively, for example: x = j = 10, or (x=10) = 100; The return value of the assignment operator must be an lvalue so that it can be assigned again. The reference is therefore the only return value selection for this operator.

#include<iostream.h>

int &put (int n);

int vals[10];

int error=-1;

void Main ()

{

Put (0) = 10; The value of the put (0) function as the left value is equivalent to vals[0]=10;

Put (9) = 20; The value of the put (9) function as the left value 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) In some other operators, it is not possible to return a reference: +-*/arithmetic character. They cannot return references, effective c++[1] Item23 detailed discussion of this issue. The main reason is that these four operators do not have side effect, so they must construct an object as the return value, and the optional scheme includes returning an object, returning a reference to a local variable, returning a reference to a new allocated object, and returning a static object reference. According to the preceding reference as the three rules for the return value, the 2nd and 32 scenarios are deprecated. A reference to a static object also causes an error because ((a+b) = = (C+d) is always true. So the only option left is to return an object.

11, structure and union have and difference?

(1). Structs and unions are made up of several different data type members, but at any one time, the union only holds a selected member (all members share a single address space), and all members of the struct are present (different member's storage address).

(2). For different member assignments of a union, overrides are made to the other members, and the values of the original members do not exist, and the assignments for different members of the structure do not affect each other.

12, try to write the results of the program:

int a=4;

int &f (int x)

{a=a+x;

return A;

}

int main (void)

{int t=5;

Cout<<f (t) <<endl; A = 9

F (t) = 20; A = 20

Cout<<f (t) <<endl; t = 5,a = 25

T=f (t); A = 30 T =

Cout<<f (t) <<endl; } t = 60

}

13. Overloading (overload) and rewriting (overried, some books are also called "overlays") the difference?

Frequently-tested topics. In terms of definition:

Overloading: means that multiple functions with the same name are allowed, and the parameter tables of these functions are different (perhaps the number of arguments is different, perhaps the parameter types are different, perhaps the two are different).

Overriding: Refers to a subclass of methods that redefine the virtual function of the parent class.

From the realization principle says:

Overloading: The compiler modifies the names of functions of the same name based on a different parameter table of the function, and then the functions of the same name become different functions (at least for the compiler). For example, there are two functions of the same name: function func (p:integer): Integer, and function func (p:string): integer; Then the compiler has done a modified function name may be this: Int_func, Str_func. The invocation of these two functions has been determined and is static between the compilers. That is, their addresses are bound (early bound) at compile time, so overloading and polymorphism are irrelevant!

Rewrite: is really related to polymorphism. When a child class has redefined the virtual function of the parent class, the parent class pointer dynamically calls the function that belongs to the subclass according to the different child class pointers assigned to it, so that the function call cannot be determined during compilation (the address of the virtual function of the called subclass cannot be given). Therefore, such a function address is bound at run time (late binding).

14. What kinds of situations can only be used with intialization list and not with assignment?

Answer: When a class contains a const, reference member variable, the constructor of the base class needs to initialize the table.

is C + + type-safe?

Answer: No. Between two different types of pointers can be cast (cast with reinterpret). C # is type-safe.

What code is executed before the main function is executed?

Answer: The constructor for the global object is executed before the main function.

17. Describe how memory is allocated and how they differ?

1) allocation from a static storage area. Memory is allocated at the time of program compilation, and the entire running period of the program is present in this block. For example, global variables, static variables.

2) Create on the stack. When executing a function, the storage units of local variables within the function can be created on the stack, which are automatically freed when the function is executed at the end. The stack memory allocation operation is built into the instruction set of the processor.

3) allocation from the heap, also known as dynamic memory allocation. When the program is running, it uses malloc or new to request any amount of memory, and the programmer is responsible for freeing the memory with free or delete. The lifetime of dynamic memory is determined by programmers and is very flexible to use, but the problem is the most.

18. Write out the comparison statements for Bool,int,float, pointer-type variables A and "0" respectively.

Answer:

Bool:if (!a) or if (a)

Int:if (A = = 0)

Float:const EXPRESSION EXP = 0.000001

if (A < EXP && a >-exp)

Pointer:if (a = null) or if (a = = null)

19. What are the advantages of const versus # define?

Answer:

Const action: Defines a constant, a modifier function parameter, a modifier function return value three function. The const-modified items are protected against accidental changes and can improve the robustness of the program.

1) 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.

2) Some integrated debugging tools can debug const constants, but cannot debug macro constants.

20. Describe the difference between an array and a pointer?

Arrays are either created in a static store (such as a global array) or created on a stack. Pointers can point to any type of memory block at any time.

(1) Changes in the content of the differences

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

(2) 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.

Char a[] = "Hello World";

char *p = A;

cout<< sizeof (a) << Endl; 12 bytes

cout<< sizeof (p) << Endl; 4 bytes

Calculating the memory capacity of arrays and pointers

void Func (char a[100])

{

cout<< sizeof (a) << Endl; 4 bytes instead of 100 bytes

}

Question 21st: what does int (*s[10]) (int) mean?

An array of int (*s[10]) (int) function pointers, each pointing to a function of the int func (int param).

Question 22nd: stack memory and literal constant area

Char str1[] = "ABC";
Char str2[] = "ABC";

const char str3[] = "ABC";
const char str4[] = "ABC";

const char *STR5 = "abc";
const char *STR6 = "abc";

char *STR7 = "abc";
char *str8 = "abc";

cout << (str1 = = str2) << endl;//0 point to respective stack memory respectively
cout << (Str3 = = STR4) << endl;//0 point to respective stack memory respectively
cout << (STR5 = = STR6) << endl;//1 point to text constant area address same

cout << (STR7 = = str8) << endl;//1 point to text constant area address same

The result is: 0 0 1 1

Answer: STR1,STR2,STR3,STR4 are array variables, they have their own memory space, and STR5,STR6,STR7,STR8 are pointers that point to the same constant area.

Question 23rd: Jump The program to the specified memory address

To assign a value to the absolute address 0x100000, we can use (unsigned int*) 0x100000 = 1234; So if you want the program to jump to the absolute address is 0x100000 to execute, what should be done?


* ((Void (*) ()) 0x100000) ();
The first step is to cast the 0x100000 into a function pointer, which is:
(Void (*) ()) 0x100000
And then call it again:
* ((Void (*) ()) 0x100000) ();
With typedef you can see more intuitively:
typedef void (*) () voidfuncptr;
* ((VOIDFUNCPTR) 0x100000) ();

Question 24th: int id[sizeof (unsigned long)]; Is this right? Why?


Answer: Correct this sizeof is a compile-time operator, which is determined at compile time and can be viewed as a machine-related constant.

Question 25th: What is the difference between a reference and a pointer?


"Reference Answer"
1) The reference must be initialized, and the pointer does not have to.

2) The reference initialization cannot be changed and the pointer can change the object being referred to.

3) There is no reference to a null value, but there is a pointer to a null value.

Question 26th: What are the advantages of const compared to #define?


"Reference Answer"

(1) 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 (marginal effects).

(2) Some integrated debugging tools can debug const constants, but cannot debug macro constants.

Question 27th: Complex declarations

void * (* (*FP1) (int)) [10];

Float (* (* FP2) (int,int,int)) (int);

Int (* (* fp3) ()) [10] ();

What does that mean?
Standard answer

1.void * (* (*FP1) (int)) [10]; FP1 is a pointer to a function whose arguments are of type int, and the return value of the function is a pointer to an array of 10 elements, each of which is a void*-type pointer.

2.float (* (* FP2) (int,int,int)) (int); FP2 is a pointer to a function that has a parameter of 3 int, and the return value of the function is a pointer to a function that has a parameter of type int and the return value of the function is of type float.

3.int (* (* fp3) ()) [10] (); FP3 is a pointer to a function, the function's parameters are empty, the function's return value is a pointer to an array, the array has 10 elements, each element is a pointer to a function, the function's parameters are empty, the function's return value is the int type.

Question 28th: How many kinds of memory are allocated?

"Reference Answer"

One, the allocation from the static storage area. Memory is allocated at the time of program compilation, and the entire running period of the program is present in this block. For example, global variables.

Second, create on the stack. When executing a function, the storage units of local variables within the function can be created on the stack, which are automatically freed when the function is executed at the end. The stack memory allocation operation is built into the processor's instruction set and is highly efficient, but allocates limited memory capacity.

Third, the allocation from the heap, also known as dynamic memory allocation. When the program is running, it uses malloc or new to request any amount of memory, and the programmer is responsible for freeing the memory with free or delete. The lifetime of dynamic memory is determined by us and is very flexible to use, but the problem is the most.

Question 29th: What is the problem when the destructor of the base class is not a virtual function?

"Reference answer" the destructor of a derived class is not used, which can cause a resource leak.

Question 30th: 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?

"Reference Answer"

Different life cycle:

The global variables are created and created by the main program, destroyed by the main program, and local variables exist inside local functions, even within local loop bodies, and exits do not exist;

The use of different ways: through the declaration of the various parts of the global variables 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.

C + + common face test 30 road

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.