Study Notes on addresses, pointers, and reference variables in C/C ++ (10): Reference Variables

Source: Internet
Author: User
Tags call by reference date now

The quote type is similar to the pointer type. The pointer can also be used for any task that can be referenced, but its syntax does make up for many defects of the pointer.

 

The commonalities between references and pointers:

--- Both can be used as function parameters and return values

--- Function calls that return a reference or address (pointer) can appear on any side of the value assignment.

 

Differences between references and pointers:

--- Reference is the logical alias of the actual variable

--- The reference must be initialized with an actual variable during the declaration.

--- Reference cannot be changed after Initialization

--- Null reference does not exist

 

References in C ++ are aliases of other variables. To declare a referenced variable, you need to give it an initial value. In the life cycle of a variable, this value cannot be changed.

You can use the & operator to define referenced variables.

For example:

Int actualint;

Int & otherint = actualint;

These two statements declare an integer named "actualint. All operations on these two identifiers will have the same effect.

# Include <iostream> </P> <p> //////////////////////////// /// // <br/> // The main () function. <br/> //////////////////////////////////// //// <br/> int main () <br/>{< br/> int actualint = 123; <br/> Int & otherint = actualint; </P> <p> STD :: cout <actualint <STD: Endl; <br/> STD: cout <otherint <STD: Endl; </P> <p> otherint ++; <br/> STD: cout <actualint <STD: Endl; <br/> STD: cout <otherint <STD: Endl; </P> <p> actualint ++; <br/> STD: cout <actualint <STD: Endl; <br/> STD :: cout <otherint <STD: Endl; </P> <p> return 0; <br/>}

Running result:

Note:

The reference is neither a copy of the original object nor a pointer to the original object. In fact, the compiler uses it as another name of the original object.

The following code compares the addresses of the two to demonstrate that the alias metaphor is appropriate.

# Include <iostream> </P> <p> //////////////////////////// /// // <br/> // The main () function. <br/> //////////////////////////////////// //// <br/> int main () <br/>{< br/> int actualint = 123; <br/> Int & otherint = actualint; <br/> STD :: cout <& actualint <''<& otherint; </P> <p> return 0; <br/>}

The running result is as follows:

 

Initialization reference:

Unlike pointers, the value of a referenced variable cannot be changed. When a real variable is referenced, the alias must be initialized (explicitly specifying its referenced object) unless one of the following conditions is met:

--- The referenced variable is declared as an external (extern) and can be initialized anywhere.

--- The referenced variable is a member of the class and initialized in the constructor.

--- The referenced variable is used as the form parameter in the function declaration. During the function call, the caller's real parameters are used for initialization.

 

Use references to simplify complex expressions

When some expressions need to get objects from array elements and structures, you can use references to simplify complex expressions. Especially when a long string of expressions needs to be repeatedly used to obtain a specific element, the reference is extremely convenient.

# Include <iostream> </P> <p> // a date structure. <br/> struct date <br/>{< br/> int month, day, year; <br/> }; </P> <p> // an employee structure. <br/> struct employee <br/> {<br/> int empno; <br/> char name [35]; <br/> date dates [3]; // hired, last review, terminated. <br/> float salary; <br/>}; </P> <p> employee staff [] = <br/>{< br/> {1, "Bill", {35000, 88 },{, 92 },{, 95 }}, },< br/> {1, "Paul ",{ {25000, 87}, {, 94}, {,}, <br/> {1, "Jim", {, 80 }, {9, 11, 96 },{ 0, 0 }}, 42000 },< br/> {0} <br/> }; </P> <p> ///////////////////////////////// //// // <br/> // The main () function. <br/> //////////////////////////////////// //// <br/> int main () <br/>{< br/> employee * pempl = staff; <br/> while (pempl-> empno! = 0) <br/>{< br/> for (INT I = 0; I <3; I ++) <br/>{< br/> Date & RD = pempl-> dates [I]; <br/> STD: cout <Rd. month <'/' <br/> <Rd. day <'/' <br/> <Rd. year <""; <br/>}< br/> STD: cout <STD: Endl; <br/> pempl ++; <br/>}</P> <p> return 0; <br/>}

The running result is as follows:

 

Used as a reference of function parameters

References are often used as the form parameters of a function. If the reference is only within the scope of the variable, it has almost no effect. simply use the original name of the variable.

Advantages of using reference instead of real parameter copy as a form parameter:

--- Avoid extra overhead caused by transferring large data structures.

--- You do not need to use operators such as * and-> like pointers.

# Include <iostream> </P> <p> // a big structure. <br/> struct bigone <br/>{< br/> int serno; <br/> char text [1000]; <br/> }; </P> <p> // two function prototypes with a structure parameter. <br/> void slowfunc (bigone P1); // call by value. <br/> void fastfunc (bigone & P1); // call by reference. </P> <p> ///////////////////////////////// //// // <br/> // The main () function. <br/> //////////////////////////////////// //// <br/> int main () <br/>{< br/> static bigone BO = {123, "This is a big structure "}; </P> <p> // this call will take a while. <br/> slowfunc (BO); </P> <p> // this call will be faster than the previous one. <br/> fastfunc (BO); </P> <p> return 0; <br/>}</P> <p> //////////////////////////// /// // <br/> // a call-by-value function. <br/> //////////////////////////////////// //// <br/> void slowfunc (bigone P1) <br/>{< br/> STD: cout <p1.serno <STD: Endl; <br/> STD: cout <p1.text <STD :: endl; <br/>}</P> <p> //////////////////////////// /// // <br/> // a call by reference function. <br/> //////////////////////////////////// //// <br/> void fastfunc (bigone & P1) <br/>{< br/> STD: cout <p1.serno <STD: Endl; <br/> STD: cout <p1.text <STD :: endl; <br/>}

The running result is as follows:

 

Call a function as a reference

When a function passes a reference as a parameter to another function, the called function directly performs operations on the parameter copy of the caller, instead of generating a local copy (passing the variable itself is like this ). This is called calling by reference, and passing the parameter value to the copy inside the called function is called calling by passing the value.

# Include <iostream> </P> <p> // Date structure. <br/> struct date <br/>{< br/> int month, day, year; <br/>}; </P> <p> // function prototypes. <br/> void display (const Date &, const char *); <br/> void Swapper (Date &, Date &); </P> <p> ///////////////////////////////// //// // <br/> // The main () function. <br/> //////////////////////////////////// //// <br/> int main () <br/> {<br/> // define two dates. <br/> static date now = {2, 23, 90}; <br/> static date then = {9, 10, 60 }; </P> <p> // display the dates. <br/> display (now, "now:"); <br/> display (then, "then :"); </P> <p> // swap the dates and redisplay them. <br/> Swapper (now, then); <br/> display (now, "now:"); <br/> display (then, "then :"); </P> <p> return 0; <br/>}</P> <p> //////////////////////////// ////////// <br/> // swap the caller's dates. <br/> //////////////////////////////////// //// <br/> void Swapper (Date & dt1, date & dt2) <br/>{< br/> date save; <br/> Save = dt1; <br/> dt1 = dt2; <br/> dt2 = save; <br/>}</P> <p> //////////////////////////// //// // <br/> // display a date object. <br/> //////////////////////////////////// //// <br/> void display (const Date & DT, const char * TTL) <br/>{< br/> STD: cout <TTL; <br/> STD: cout <DT. month <'/' <br/> <DT. day <'/' <br/> <DT. year <STD: Endl; <br/>}

The running result is as follows:

 

Reference as function return value

Of course, when a function returns a reference, the call to the function can appear anywhere the reference can appear, including the acceptor of the value assignment.

# Include <iostream> </P> <p> // a date structure. <br/> struct date <br/>{< br/> int month, day, year; <br/> }; </P> <p> // an array of dates. <br/> date birthdays [] = <br/>{< br/> {12, 17, 37 },< br/> {10, 31, 38 }, <br/> {6, 24, 40}, </P> <p> {11, 23, 42}, <br/> {8, 5, 44 }, <br/> }; </P> <p> ///////////////////////////////// ///// <br/> // a function to retrieve a date. <br/> //////////////////////////////////// /// <Br/> const Date & getdate (int n) <br/>{< br/> return birthdays [n-1]; <br/>}</P> <p> //////////////////////////// /// // <br/> // The main () function. <br/> //////////////////////////////////// //// <br/> int main () <br/>{< br/> int dt = 99; <br/> while (DT! = 0) <br/>{< br/> STD: cout <STD: Endl <br/> <"enter date # (1-5, 0 to quit): "; <br/> STD: CIN> DT; </P> <p> If (DT> 0 & dt <6) <br/>{< br/> const Date & BD = getdate (DT); <br/> STD: cout <BD. month <'/' <br/> <BD. day <'/' <br/> <BD. year <STD: Endl; <br/>}</P> <p> return 0; <br/>}

The running result is as follows:

 

Reference and pointer usage principles:

1. If the variable to be pointed to does not exist, use the pointer. For pointer parameters, a null address can be used to indicate that the variable does not exist, while a null reference does not. If you are sure that the variable exists, use the reference.

2. If the program must traverse the array of objects, you should consider using pointers. In this case, the arithmetic operators of pointers are generally more efficient than the subscript representation used for reference. For the latter, the program requires two variables: Reference and subscript. For the former, only one variable is required.

3. the pointer can also complete the work that can be referenced. One improvement of referenced variables on pointers is that the value of referenced variables cannot be changed, but a new object address can be obtained through arithmetic operations of pointers, which reduces a lot of trouble. Once a referenced variable is correctly initialized to point to an object, it cannot be pointed to another place, especially the location it should not point.

4. Referencing can avoid using pointers to obtain the complex representation required by objects.

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.