C + + common face test __c++

Source: Internet
Author: User
Tags inheritance
Reproduced from: http://blog.csdn.net/wangshihui512/article/details/9092439
1.new, delete, malloc, free relationship

Delete calls the destructor of the object, and the new free only frees up memory and new calls the constructor. malloc and free are standard library functions for c++/c languages, and new/delete are the operators of C + +. Both can be used to request dynamic memory and free memory. For objects that are not internal data types, Maloc/free cannot meet the requirements of dynamic objects. Objects are created with the constructor automatically executed, and the destructor is automatically executed before the object dies. Because Malloc/free is a library function and not an operator, it is not possible to impose the task of executing constructors and destructors on Malloc/free without the compiler controlling permissions. The C + + language therefore requires a new operator to complete dynamic memory allocation and initialization, as well as an operator delete that cleans and frees up memory work. Note that New/delete is not a library function. 2.delete differs from delete []

Delete Calls only a destructor, and delete[] invokes the destructor of each member. In more effective C + + There is a more detailed explanation: "When the delete operator is used for an array, it calls the destructor for each array element, and then calls the operator delete to free the memory." "Delete is matched with new, delete [] with new [] matching

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-

The error is in the division.

This means that the delete and delete[] features are the same for built-in simple data types. For custom complex data types, delete and delete[] are not interoperable. Delete[] Deletes an array, delete deletes a pointer. In simple terms, the memory allocated with new is deleted with delete, and the memory allocated with new[] is deleted with delete[. Delete[] invokes the destructor of the array element. The internal data type does not have a destructor, so the problem is small. If you use delete without parentheses, delete will think that it points to a single object, otherwise it will think that it points to an array. What are the properties of 3.c++ (object-oriented features)

Encapsulation, inheritance, and polymorphism. 4. To invoke the destructor of the parent class when the subclass is destructor.

The order of the destructor calls is to derive the destructor of the base class after the destructor of the class, that is to say, the information of the derived class has been completely destroyed when the destructor of the base class is invoked. The constructor of the base class is called first when an object is defined, and then the constructor of the derived class is called, and the destructor is reversed: The destructor of the derived class is called first, and then the destructor of the base class is called. 5. Polymorphic, virtual function, pure virtual function

Polymorphism: A different action occurs when a different object receives the same message. The polymorphism of C + + is embodied in two aspects of running and compiling: The polymorphism of the program runtime is embodied by inheritance and virtual function;

The polymorphism is embodied in the overload of functions and operators when the program compiles;

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

function of a pure virtual function: Preserve the name of a function for its derived class in the base class so that the derived class defines it as needed. As an interface, there is no function of pure virtual function, which can not be called directly.

A pure virtual function inherited from a base class that 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, not for creating object instances directly. However, you can still support run-time polymorphism with pointers to abstract classes. 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;

}

Suppose x = 9999. Answer: 8

Train of thought: Convert X to 2 to see the number of 1 contained. 7. What is a "reference". The issues to be noted and the use of references.

A: A reference is the alias of a target variable, and the action applied is exactly the same as the direct manipulation of the variable. When you declare a reference, remember to initialize it. After the reference declaration is complete, it is equivalent to the target variable name with two names, that is, the target's original name and reference name, and the reference name cannot be used as an alias for another variable name. Declaring a reference, not a newly defined variable, only indicates that the reference name is an alias of the target variable name, it is not a data type itself, so the reference itself does not occupy the storage unit and the system does not allocate the storage unit to the reference. Cannot establish a reference to an array. 8. What are the characteristics of a "reference" as a function parameter?

(1) The effect of passing a reference to a function is the same as passing a pointer. At this time, the parameter of the function is called the real parametric or an alias of the object in the original keynote function, so the operation of the parameter variable in the modulated function is the operation of its corresponding target object (in the keynote function).

(2) using the parameter of the reference pass function, there is no copy of the argument in memory, it is a direct operation of the argument, while using a generic variable to pass the function's arguments, when a function call is made, the parameter is required to allocate the storage unit, the parameter variable is a copy of the argument variable, and the copy constructor is called if the object is passed. Therefore, when the parameter passes the data is big, uses the reference to pass the parameter with the general variable the efficiency and occupies the space to be good.

(3) The use of pointers as a function of the parameters, although also can achieve the effect of using references, however, it is very easy to make errors and poor reading of the program in the same way that the parameters are allocated to the parameters, and the "* pointer variable name" needs to be used repeatedly. On the other hand, at the call point of the calling function, You must use the address of the variable as an argument. And references are easier to use and clearer. 9. When you need to use the "constant reference".

If you want to use the reference to improve the efficiency of the program, but also protect the data passed to the function is not changed in the function, you should use the constant reference. Constant 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 Foo () and the "Hello World" string all produce a temporary object, whereas in C + + These temporary objects are const types. So the expression above is an illegal attempt to convert a const-type object to a non-const type. Reference parameters should be defined as const if they can be defined as const.

10. Use "Reference" as a function return value type format, benefits, and rules to follow?

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

Benefit: No copy of the returned value is generated in memory; (note: For this reason, it is undesirable to return a reference to a local variable.) Because with the end of the local variable lifetime, the corresponding reference is invalidated, resulting in runtime error!

Precautions:

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

(2) cannot return a reference to the memory allocated by the function's internal new. This can refer to item 31 of effective c++[1]. Although there is no problem of passive destruction of local variables, it can be faced with other embarrassing situations in this case (returning the reference of allocating memory within new function). For example, a reference returned by a function only appears as a temporary variable without being given an actual variable, so the space that the reference points to (allocated by new) cannot be released, causing memory leak.

(3) You can return a reference to a class member, but preferably a const. This principle can refer to item 30 of effective c++[1]. The main reason is that when an object's properties are associated with a certain business rule (business rules), the assignment is often related to the state of some other property or object, so it is necessary to encapsulate the assignment operation in one business rule. If other objects can get a very strong reference (or pointer) to the property, then a simple assignment to that property can break the integrity of the business rule.

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

Stream operators << and >>, these two operators often want to be used continuously, for example: cout << "Hello" << Endl; So the return value of these two operators should be a stream reference that still supports both operators. Alternative alternatives include: returning a Stream object and returning a stream object pointer. But for returning a stream object, the program must recreate (copy) a new stream object, that is, the continuous two << operators are actually for different objects. It's not acceptable. The << operator cannot be used continuously for returning a stream pointer. Therefore, returning a Stream object reference is the only choice. The only option is critical, which illustrates the importance and irreplaceable nature of references, and perhaps that's why the concept of referencing is introduced in the C + + language.

Assignment operator =. This operation, like the Fuchang operator, can be used continuously, for example: x = j = 10; or (x=10) = 100; The return value of the assignment operator must be a left value so that it can be continued to be assigned. So the reference is 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 put (0) function value as the left value is equivalent to vals[0]=10;

Put (9) = 20; The put (9) function value 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, you must not return the reference:+-*/  arithmetic character. They cannot return the reference, Effective c++[1] 's Item23 discusses the problem in detail. The main reason is that these four operators have no 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 assigned object, and returning a static object reference. The 2nd and 32 scenarios have been deprecated, based on the three rules referred to above as the return value. A reference to a static object also causes an error because ((a+b)  ==  (c+d)) will always be true. So the only option left is to return one object.

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.