C + + Primer learning notes _17_ from C to C + + (3)--Reference, const reference, reference Pass, reference as function return value, reference to pointer difference

Source: Internet
Author: User

Welcome to read the reference, if there are errors or questions, please leave a message to correct, thank you

First, reference1.a reference is an alias for a variablevariables:nameSpaceReferences:reference is not a variablereference is simply an alias of a variableThe reference does not have its own independent spacereference to share space with the variable it referencesThe change to the reference is actually a change to the variable it refers toreferences must be initialized at the time of definitiononce a reference is initialized, it cannot be re-directed to another variable
2, define the general format of the reference:(1)type & Reference name = variable name; (2) For example:
int A=1;int &b=a;  B is the alias of a, so A and B are the same unit

(3) Note : When defining a reference, be sure to initialize it, indicating whose alias the reference variable is

(4) Example
#include <iostream>using namespace Std;int main (void) {int val =;//int& refval; Error, reference must initialize int& refval = val; Refval = 200; Assign 200 to Refval               //Actually change val this variable cout << "val=" << val << endl; int val2 = $; refval = Val2;// Does not mean to refer refval to val2 this variable                //simply represents assigning Val2 to Refval, changing Val value cout << "val=" << Val << Endl; return 0;}
Operation Result:val=200val=500
3.in practical applications, references are generally used as parameter passing and return values

Second, const reference1.Constreferences are pointing toConstreferences to Objects

2. Example

#include <iostream>using namespace Std;int main (void) {const int val = 1024x768; Const int& refval = val;//int& Ref2 = val;//Error,nonconst reference to const object//refval = 200; Error,refval is a constant int val2 = 1024; Const int& REF3 = val2;//const reference to Nonconst object double val3 = 3.14; Const int& REF4 = VAL3; int temp = VAL3;                         Const int& REF4 = temp; cout << "ref4=" << ref4 << Endl; cout << "val3=" << val3 << Endl; int& REF5 = Val3; Error, does not produce intermediate variable return 0;}

Operation Result:

Ref4=3

val3=3.14



Third, reference delivery1.A reference is passed in a function definition with a reference operator before the parameter"&"For example:Swap (int &a,int &b);
2, in C language in two ways of transmission:(1)Pass by value:Pass by ValueWayeasy to understand,but the parameter valuethe Changecannot have an effect on an argument(2)Pointer passing: The address transfer mode changes the corresponding arguments by changing the parameters,But the program is prone to error and difficult to read
3. In C + +,Reference as parameterAny operation on a formal parameter iscan change the data of the corresponding arguments, and makes the function callIt seems convenient and natural(1) Value pass argument to initial taxiing parameter to allocate space, copy the argument contents to the formal parameter(2) No space allocated when a reference pass argument initializes a new parameter(higher efficiency)(3) The pointer transfer essence is the value pass, and the argument's initial taxiing parameter also allocates the pointer Space (4 bytes). If we want to change the address of the pointer, simply passing the pointer is not possible.
4. Example:

#include <iostream>using namespace std;void swap (int &x, int &y); int main () {    int A, b;    A = ten;    b =;    Swap (A, b);  When a function is called, the reference is initialized by x = A, y = b;    cout << "A=" << a << "b=" << b << Endl;    return 0;} void swap (int &x, int &y) {    int temp;    temp = x;    x = y;    y = temp;}

Operation Result:

a=20b=10



Iv. Reference as function return value1, another function of the reference is to return the referenced function
2. Functionsreturn Referenceof aMain PurposeIsThe function can be placed to the left of the assignment operator。 (1) Example
#include <iostream>using namespace std;//reference as function return value int a[] = {0,1,2,3,4};int& index (int i) {return a[i];  Global variable}int main (void) {index (3) = 100;//reference as a function return value so that the function can be placed on the left of the assignment operator                 //function return reference, the reference is initialized when the function returns                 //Index (3) Initialized to A[3 when the function returns);  cout << "a[3]=" << a[3] << Endl; return 0;}
Operation Result: a[3]=100

3.Note: You cannot return a reference to a local variable. (1) Example
#include <iostream>using namespace std;int& Add (int a, int b) {int sum; sum = a + B; return sum;//cannot return a reference to a local variable }int Main (void) {int n = Add (3, 4); int& N2 = Add (5, 6);//N2 is a reference, no self-contained space                      //N2 value depends on the variable it references                      //If the life of the variable referenced by N2 Period is over, meaning that N2 is a                      //invalid reference, then the value of N2 will be indeterminate. cout << "n2=" << n2 <<endl; may not be covered by n, so correct cout << "n=" << n << Endl; cout << "n2=" << n2 << Endl; return 0;}
Operation Result:
n2=11
n=7n2=20395849

v. differences between references and pointers 1.ReferencesAccessing a variable isDirect Access, whilePointersIsIndirect Access。 2.ReferencesIs the alias of a variable, itselfnot individually assignedof their ownMemory Space, whilethe pointer has its own memory space。 3.ReferencesOnce initializedno more references to other variables, whilepointers can be。4. Use references whenever possible, use pointers when necessary.



Reference:

C + + Primer Fourth Edition

C + + Primer Fifth Edition


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

C + + Primer learning notes _17_ from C to C + + (3)--Reference, const reference, reference Pass, reference as function return value, reference to pointer difference

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.