C ++ reference type

Source: Internet
Author: User

Let's first look at a simple program to explain the basic knowledge of reference.

# Include <cstdlib> <br/> # include <iostream> <br/> using namespace STD; <br/> int main (void) <br/>{< br/> int * P; <br/> int A = 5; <br/> int B = 6; <br/> Int & C = A; // B indicates a reference. When defining B, A must be a live object. <br/> P = &; <br/> // P = 6; invalid <br/> cout <"before increment P:" <p <Endl; <br/> P ++; // P ++ can be equal to the size of the int to be automatically moved back <br/> cout <"after increment P: "<p <Endl; // You Can See That Int Is 4 bytes <br/> P --; // point back to the original memory <br/> cout <"before reassignment:" <Endl; <br/> cout <"the value * P: "<* P <Endl; <br/> // In fact, referencing this object is not like a variable or pointer. It can be understood as an alias mechanism, and once the reference is bound, other variables cannot be referenced in the future <br/> cout <"the value of C (that is ): "<C <Endl; <br/> // whether to assign a value to the reference or to the referenced variable, the value of this memory unit changes <br/> cout <"After reassignment:" <Endl; <br/> C = 7; <br/> cout <"the value of A:" <A <Endl; <br/> cout <"the value of * P: "<* P <Endl; <br/> // at this time, executing c = B actually assigns the value of B to C (or ), it does not mean that C is changed to B <br/> C = B; <br/> cout <"the value of A:" <A <Endl; <br/> cout <"the value of C:" <C <Endl; <br/> cout <"the value of & C (that is the address of a):" <& C <Endl; <br/> cout <"the address of B:" <& B <Endl; <br/> // However, the pointer can be directed to another memory unit. and the reference does not need to show the memory space to be recycled. The Compiler completes <br/> cout <"before re-pointing, P:" <p <Endl; <br/> P = & B; <br/> cout <"after re-pointing, P:" <p <Endl; <br/> system ("pause"); <br/> return 1; </P> <p >}< br/>

 

C ++ has one more class type than C: reference. This variable is not changed.
Pointer is not like a pointer. Sometimes it can be understood as an alias mechanism.

A reference refers to a reference to an object. So what is an object? In C ++, objects in the narrow sense refer
Variables declared using complex data types such as class, structure, and Union, such as myclass and cdialo
G mydlg. Generalized objects include variables declared using int, Char, float, and other simple types.
Such as int A and char B. The term "object" is a broad object. C ++
It is helpful for beginners to look at reference books by setting up the concept of this broad object.
Most books only use the word "object". For this word, there are two concepts: broad and narrow.
.

I. Reference Basic Features

First, let's declare a reference and use it to preliminarily understand the reference.
Example 1:
1. Int v, k, h;
2. Int & Rv = V;
3. Rv = 3; // at this time, the value of V is also changed to 3.
4. V = 5;
5. K = RV + 2; // K = 5 + 2 = 7.
6. H = 12;
7. Rv = h;
8. Rv = 20;
The first clause declares three objects (simple variables ).
The 2nd clause declares a reference named RV, which has the int type, or is
References the int type, and it is initialized to be "Bound" with the int type object v. R
V is called the reference of object v.
In the first sentence, the RV value is assigned to 3. The magic of reference is here, while changing the reference value
Changed the value of the object bound with the reference. So the value of V also changes to 3.
In the first sentence, the V value is changed to 5, and the reference value pointing to V is also changed to 5. Therefore
The value is 5 + 2 equals 7.

The preceding five sentences describe the relationship between the referenced and bound objects: they are linked in numerical values and change you.
It changes me, and it changes you. In fact, the reference of the access object and the access object is
Is used to access the same memory area.

Sentences 6, 7, and 8 describe another feature of reference: one end. What does it mean? When you reference
After a reference is bound to an object in the declaration statement
It can't be changed. So this is why I used the word "binding. Different pointers
. After the pointer is initialized to point to an object in the pointer declaration statement
You can also change it to another object. Therefore, assigning an RV value to h in the first sentence does not mean that this reference
The RV is rebound to H. In fact, the first sentence is just a simple assignment statement. After execution, RV and
The values of V are changed to 12. After 8th sentences are executed, the values of RV and V are both 20, while the values of H remain unchanged by 12.

There is also a feature for reference: the object to which the reference is bound must be initialized during declaration.
. (In fact, if you think of int float and other types as generalized classes, define an int A. The memory space is already

Allocated. Int & B =. The key is that when an object is referenced, the object

Make sure that the memory has been allocated and there is space.) We all know that the pointer can be declared without initialization, but the reference won't work. Therefore, the following statements cannot be passed
Compiled:
Int V;
Int & RV;
Rv = V;

Another example:
Example 2:
Class myclass
{
Public:
Int;
...
...
};

Myclass;
Myclass & CC = myclass;
Myclass. A = 20; // equivalent to CC. A = 20
Cc. A = 60; // equivalent to myclass. A = 60

As shown in the preceding example, no matter how complicated the object is, you can reference or use the object.
The object itself is in the same syntax format. In essence, we use the same partition in the memory.
Domain.
The syntax for getting a referenced address is the same as that for getting an object address.
Symbol "&". For example:
Int I;
Int & Ri;
Int * Pi = & Ri; // This sentence serves the same purpose as int * Pi = & I.
Of course, getting the address of an object is the same as getting the address referenced by this object.
.

II. The role of reference in function parameter passing (this concept is very important)

Now let's further understand the reference through the function parameter transfer mechanism. In C ++, give a function
There are three methods for passing parameters: 1. Passing the object itself. 2. Pass the pointer to the object. 3. Passing objects
.
Example 3:
Class myclass
{
Public:
Int;
Void method ();
};

Myclass;

Void fun1 (myclass );
Void fun2 (myclass *);
Void fun3 (myclass &);

Fun1 (myclass); // After the function is called, myclass. A = 20 remains unchanged.
Fun2 (& myclass); // After the function is called, myclass. A = 60, changed.

Fun3 (myclass); // After the function is called, myclass. A = 80, changed.

// Pay attention to the real parameters of fun1 and fun3, and prove again: Use object and use Object Reference
The syntax format is the same.

Void fun1 (myclass MC)
{
MC. A = 40;
MC. Method ();
}

Void fun2 (myclass * MC)
{
Mc-> A = 60;
Mc-> method ();
}

Void fun3 (myclass & Mc)
{
MC. A = 80;
MC. Method ();
}
We have an object of the myclass type, myclass, and three functions, fun1, fun2, and fun3.
The functions must take the object itself as the parameter, the pointer to the object as the parameter, and the object reference as the parameter.
Number.

Please refer to the fun1 function. It uses the object itself as the parameter. This parameter passing method is called the value passing method.
. C ++ will generate a copy of The myclass object and pass the copy to the fun1 function. In fun1 Function
The member variable A of MC is modified internally, but the copied member variable A is not affected at all.
A is a member variable of myclass as a real parameter.
The fun2 function uses a pointer to the myclass type as a parameter. In this function, the MC Institute is modified
The member variable A of the object to be directed to. This actually modifies the member variable A of the myclass object.
Fun3 uses the reference of the myclass object as the parameter, which is called the reference transfer method. Modified
Member variable A of MC. As mentioned earlier, accessing an object and accessing the reference of this object are actually accessing
Ask about the same memory area, so this will directly modify the member variable A of myclass.

From the function bodies of fun1 and fun3, we can also see that using objects and using object references are in the syntax format
Is the same.

In fun1, C ++ transfers a copy of the real parameter to the form parameter. Therefore, if the real parameter occupies a large memory
System overhead in parameter passing will be very high. In fun2 and fun3
Only the address of the real parameter is passed to the parameter, which is four bytes at best.
Small.

3. Returns the referenced function.

Reference also has a very useful feature: If a function returns a reference type,
Functions can be used as left values. Don't worry about what is the left value. You just need to know: if an object
Or the expression can be placed on the left of the value assignment number, so this object and expression are called the left value.
Here is an example that is useless but very informative:
Example 4:
1. Int I;
2. Int & F1 (Int &);
3. Int F2 (INT );
4. F1 (I) = 3; // I is obviously of the int type. Why is it Int?
5. F2 (I) = 4;

Int & F1 (Int & I)
{
Return I;
}

Int F2 (int I)
{
Return I;
}
Compile the code and you will find that 4th sentences are correct and 5th sentences are wrong. For this example
The reference is passed to F1, and F1 returns the reference as it is. The meaning of the 4th sentence is the same as that of I = 3.

I checked the book and referenced this feature to be used in heavy-duty operators. However, I perform the reload operation
It is still confusing, so we cannot give an example.
Emphasize a small problem and see what is wrong with the following code:

Int & F1 ();

F1 () = 5;
...
...
Int & F1 ()
{
Int I;
Int & rI = I;
Return Ri;
}

Note that the reference Ri returned by function F1 is declared in the function body. Once the function returns
Number scope, RI points to the memory area, that is, the memory area occupied by object I is withdrawn, and then
An error occurs when you assign values to the disk memory area.

4. Conversion of reference

In the preceding example, all referenced types are int type, and these references are initialized to bind
To int type objects. Then we imagine whether a reference can be declared, which has the int type but is
Initialize an object bound to a float type? See the following code:
Float F;
Int & Rv = F;
The result shows that the conversion cannot be compiled by msvc ++ 6.0. However, the conversion of references is not completely different.
Possible, in fact, a reference of the base class type can be initialized and bound to a derived class object, as long as
Two conditions: 1. The specified base class is accessible. 2. The conversion is unambiguous. For example:
Example 5:
Class
{
Public:
Int;
};
Class B: public
{
Public:
Int B;
};
A oa;
B ob;
A & Mm = ob;
Mm. A = 3;

We have a base class A and a derived class B, and a base class Object OA and a derived class Object OB, we
It also declares a reference to mm, which has a base class type but is bound to the derived class Object ob. Because of our
Both classes are very simple and satisfy the two conditions. Therefore, this code is legal. In this example,
Mm and the base class sub-objects in the derived class ob share a memory unit. Therefore, the statement mm. A = 3 is equivalent
Ob. A = 3, but the expression mm. B is invalid, because the base class sub-object does not include the member of the derived class.
.

5. Summary

Finally, let's summarize the references:
1. Objects and object references are a thing in a sense.
The same memory zone is accessed.
2. The syntax format of using an object is the same as that of using an object reference.
3. The reference must be initialized.
4. After a reference is bound to an object during initialization, it can only be bound to this object forever.
5. The reference of the base class type can be bound to the object of the derived class of the base class, as long as the base class and the derived class meet
The two conditions mentioned in this article. In this case, the reference is actually a reference of the base class sub-object in the derived class object.
.
6. When passing an object reference to a function, only the address of the object is passed.
Low Consumption. Accessing the form parameter in the function body actually accesses this object as the real parameter.
7. If a function returns a reference, the function call expression can be used as the left value.

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.