Comparison of pointers and references

xiaoxiao2021-03-06  197

In the process of summarizing the function parameters, let me have a further understanding of the reference type. The reference type (Reference) is a new type of C (compared to C), in many cases, it provides the same capabilities with the pointer operation. And in many cases, the use of reference is a better way.

Since we are here to compare pointers and applications, then you must first clear the specific meaning of reference. The reference is a constant pointer, that is, once reference is assigned, it is not allowed to change, which is the same as that other types of Const variables, while the declaration must be assigned, otherwise it is unable to compile. (Since You CAN't Change The Reference After You Define It, You Must Bind The Reference To An Object At The Beginning of Its Lifetime.) [1]

The first point, using the reference type, the code is automatically solved in the compiler, without the use of pointers, using the pointer, using the solution reference operator (*). This makes the code more clear and easy to read. This is particularly obvious when using the ENUM type. Below is an example:

[2] ENUM DAY

{Sunday, Monday, Tuesday,

Wednesday, Thursday, Friday,

Saturday, not_a_day

}

Day d;

D = Sunday;

While (D <= SATURDAY)

{

// Do Something with d

D;

}

The above code cannot be compiled, because the operator does not have the DAY type, although we can use int to compile the compiler when it is declared D, it is possible to reduce the compiler for the type of inspection. Then we need to do it to overload the operator.

Day & Operator (DAY & D)

{

D = (day) (D 1);

Return D;

}

By returning a reference method, rather than the pointer, you can use the built-in operator when using this overloaded operator. But if you use it, the way is returned:

Day * Operator (Day * D)

{

* D = (day) (* D 1);

Return D;

}

When calling this operator, you have to use & D.

The second point, SWAP (A, b) This function is called, and the transmission may be both a value or reference, which is determined by the type of function. Therefore, some people think that using SWAP (& A, & B) will think is clearer, after all, this is to know that the pointer is a pointer. Here, I can't help but think of the grammar in the C #, not only the explicit statement of the function of the function is the reference or value, but also reflects when the function is called, such as SWAP (Ref A, REF B). From here you can see that C # will be more rigorous in grammar.

转载请注明原文地址:https://www.9cbs.com/read-128575.html

New Post(0)