C + + Reference type "reprint"

Source: Internet
Author: User

C + + has more than one type: reference, except for the class type. This thing variable doesn't seem to change
Volume, the pointer is not like a pointer, I did not understand it before, see the program when the reference is confused.
Recently cited a good study, small harvest, special public to the community, let beginners share.
A reference refers to a reference to an object. So what is an object? In C + +, the narrow object refers to the
Variables declared using complex data types such as class, struct, union, etc., such as MyClass Myclass,cdialo
G Mydlg, and so on. Generalized objects also include variables declared with simple types such as Int,char,float
, such as int A,char B and so on. I refer to the term "object" as a whole referring to a generalized object. C++
Of the concept of the broad object, it is very helpful to see reference books, because the big
In most books, the word "object" is used, but there is no word on the concept of both broad and narrow.
Mention

One. Basic features of references

First let's declare a reference and use it to get a preliminary understanding of the reference.
Example one:
1. int v,k,h;
2. int &rv=v;
3.      rv=3; At this point, the value of V also becomes 3.
4. v=5;
5.    k=rv+2; At this time k=5+2=7.
6. h=12;
7. Rv=h;
8. rv=20;
The 1th sentence declares three objects (simple variables).
The 2nd sentence means: A reference is declared, the name is RV, it has an int type, or it is
A reference to the int type, and it is initialized to be "bound" with the object V of type int. At this time R
V is called the reference to Object v.
The 3rd sentence assigns the RV value to 3. The magic of referencing is here, changing the value of the reference as well as
Changes the value of the object that is bound together with the reference. So at this point the value of V also becomes 3.
The 4th sentence changes the value of V to 5, at which point the value of the reference to V is also changed to 5. So the 5th sentence of the K's
The value is 5+2 equals 7.

The 5 sentences above illustrate the relationship between the reference and its bound objects: numerically they are linked, changing your
Change me, change me and change you. In fact, access to objects and access to the object's references is
is to access the same piece of memory area.

The 6th, 7, 83 sentence illustrates another feature of the reference: mindedness. What do you mean? When you are quoting
Binding a reference to an object in the declaration statement, the reference will always be bound to that object.
Fixed together, can't change. So that's why I used the word "binding". And the pointers are different.
。 When the pointer is initialized to point to an object in the declaration statement of the pointer, the pointer will be
You can also change to another object. So, in the 7th sentence, the RV assignment to H does not mean that the reference
The RV was re-bound to H. In fact, the 7th sentence is just a simple assignment statement, after execution, RV and
The value of V is changed to 12. After the 8th sentence is executed, both the RV and V values are 20, and H remains 12 unchanged.

The reference also has an attribute: the declaration must be initialized, and must indicate what object to bind the reference to
On It is known that pointers are not initialized at the time of declaration, and references do not. Therefore, the following statements will not pass through
Over-compiling:
int V;
int &rv;
Rv=v;

One more example:
Example two:
Class MyClass
{
Public
int A;
...
...
};

MyClass MyClass;
myclass& Cc=myclass;
myclass.a=20; Equivalent to Cc.a=20
cc.a=60; Equivalent to Myclass.a=60

As you can see from the above example, no matter how complex this object is, use the object's reference or use the
The object itself, in the syntax format is the same, in essence we all use the same chunk in memory
Domain.
The syntax for taking a reference to the address of an object is the same as the one that takes an address.
Character "&". For example:
int i;
int &ri;
int *pi=&ri;//The function of this sentence is the same as int *pi=&i.
Of course, take the address of an object and take the address of the object reference, the result is the same


Two. The role of references in function parameter passing

Now let's learn more about references by passing mechanisms of function parameters. Give a function in C + +
There are three ways to pass parameters: 1, to pass the object itself. 2, passing a pointer to the object. 3, passing objects
The reference.
Example three:
Class MyClass
{
Public
int A;
void method ();
};

MyClass MyClass;

void Fun1 (MyClass);
void Fun2 (myclass*);
void Fun3 (myclass&);

FUN1 (MyClass); After the function call is executed, the myclass.a=20 is not changed.
Fun2 (&myclass); After executing the function call, the myclass.a=60 is changed.

Fun3 (MyClass); After executing the function call, the myclass.a=80 is changed.

Note that fun1 and Fun3 's arguments prove again: using objects and referencing them using objects
, which is the same in syntax format.

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 type MyClass MyClass and three functions Fun1,fun2,fun3, these three
The function requires the object itself as an argument, a pointer to the object, and a reference to the object.
Number.

Take a look at the FUN1 function, which uses the object itself as a parameter, and this method of passing parameters is called the pass-through value method
。 C + + will generate a copy of the MyClass object and pass the copy to the FUN1 function. In the FUN1 function
The member variable A of the MC is modified internally, and the member variable A that modifies the copy is actually not affected
The member variable A of the MyClass that is the argument.
The FUN2 function uses a pointer to the MyClass type as a parameter. Inside this function, the MC is modified
A pointer to the member variable A of the object, which is actually modified by the member variable A of the MyClass object.
FUN3 uses a reference to the MyClass object as a parameter, which is referred to as a pass-through method. Modified inside the function.
The member variable A of the MC, as mentioned earlier, accesses an object and accesses a reference to that object, which is actually an interview
The same piece of memory area, so this will directly modify the member variable a of MyClass.

The function body from FUN1 and fun3 can also be seen, using objects and references using objects, in syntax format
is the same.

In Fun1, C + + will pass a copy of the argument to the formal parameter. So if the actual parameters account for a large amount of memory, then
The system overhead in parameter passing will be very large. In Fun2 and fun3, either the pointer that passes the argument
and argument references, only the address of the argument is passed to the parameter, at best four bytes, overhead
Very small.



Three. Returns the referenced function

References also have a useful feature: If a function returns a reference type, the
Functions can be used as lvalue values. What is left value don't understand first, just understand: if an object
Or the expression can be placed to the left of the assignment number, then this object and expression is called an lvalue.
Give an example that is useless but very illustrative of the problem:
Example four:
1. int i;
2. int& F1 (int&);
3. int f2 (int);
4. F1 (i) = 3;
5. F2 (i) = 4;

int& F1 (Int&i)
{
return i;
}

int f2 (int i)
{
return i;
}
Try compiling, you will find the 4th sentence is correct, the 5th sentence is wrong. For this example, I's
The reference is passed to F1, and then F1 returns the quote as it is, and the 4th sentence has the same meaning as the i=3.

Check the book, the reference to this feature in the overloaded operator is used more. But I'm on the overloaded operation
The character is still a blur, so I can't give an example.
Highlight a small problem and see what the following code is wrong:

int &f1 ();

F1 () = 5;
...
...
int &f1 ()
{
int i;
int &ri=i;
Return RI;
}

Note that the reference RI returned by the function F1 is declared in the body of the function, and once the function returns, it exceeds the letter
Number scope, the area of memory that the RI points to, that is, the area of memory occupied by object I is retracted, and the
The memory area of the slice is assigned an error.

Four. Converted by reference

In the previous example, the referenced types are of type int, and the references are initialized to bind
To an object of type int. Then we envision whether we can declare a reference, which has an int type, but is
Initialize an object that is bound to a float type? As shown in the following code:
float F;
int &rv=f;
The result is that such conversions cannot be compiled by msvc++6.0. But the referenced conversion is not completely
It is possible, in fact, that a reference to a base class type can be initialized to bind to a derived class object, as long as it satisfies the
Two conditions: 1, the specified base class is accessible. 2, the conversion is no ambiguity. As an example:
Example five:
Class A
{
Public
int A;
};
Class B:public A
{
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 there is a base class object for OA and derived class object OB, we
Also declares a reference mm, which has a base class type but is bound to the derived class object ob. Because of our
These two classes are simple enough to satisfy those two conditions, so this code is legal. In this case,
The base class sub-object in mm and derived class OB is a common memory unit. So, the statement mm.a=3 equivalent to
Ob.a=3, but the expression mm.b is illegal because the base class sub-object does not include members of the derived class



Five. Summarize

Finally, summarize the quote:
1. References to objects and objects are in a sense something that accesses objects and accesses objects in fact
Access is the same piece of memory area.
2. The use of objects and references to objects using them are the same as in the syntax format.
3. The reference must be initialized.
4. After the reference is bound to an object in the initialization, the object will only be bound forever.
5. A reference to a base class type can be bound to a derived class object of that base class, as long as the base class and derived class satisfy the
The two conditions mentioned in the article. At this point, the reference is actually a reference to the base class child object in the derived class object

6. When a reference to a function is passed by reference, only the address of the object is passed
The system consumes less. Accessing the parameter in the function body actually accesses the object as an argument.
7. If a function returns a reference, the function call expression can be left-valued.



Six. Other
1. The code in this article has been debugged in msvc++6.0.
2. The example in section fourth, "referenced conversions":
float F;
int &rv=f;
View bc++3.1 's information, which is said to be legal. At this point the compiler generates a float type of temporary
object, the reference RV is bound to this temporary object, which means that RV is not a reference to f at this time. Don't know
What is the use of this feature in Tao bc++3.1.
3. You can declare such a reference in msvc++6.0:
const INT &rv=3;
The RV value is 3 and cannot be changed. This may not be of any use. Because if we're going to make
There are more common ways to represent constants with a single symbol:
#define RV 3
4. Change the example in section fourth a little bit:
float F;
int &rv= (int&) F;
At this point, it can be compiled by msvc++6.0. The RV is now bound to F, and RV and F share a piece of
Storage area. However, since the type of the reference RV is int, the storage area is accessed by RV
is interpreted as an integer, and the contents of the store are interpreted as real numbers when access to the storage area is obtained through F.

Http://www.cnblogs.com/wackelbh/archive/2009/12/29/1984064.html

C + + Reference type "reprint"

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.