Reference of C + +

Source: Internet
Author: User

1.1 Reference Define

The reference variable is an alias (so, not allocate memory), Once the reference are initialized to a variable, you can use The reference name or variable name to the variable.

#include <iostream>usingnamespace  std; int Main () {    int;       // declare simple variables    int &b = A;       // Declare reference variables & read as reference }
    • References need to be added & when they are defined; You cannot add & when you use them, and add & to address them when you use them.
    • You cannot establish a reference to an array (Wrong,int &&r=n) because the array is a collection of several elements, so you cannot create an alias for an array.
    • Referenced references cannot be established (Wrong,int &*p) and pointers to references cannot be established. Because the reference is not a data type, there is no referenced reference, no reference to the pointer.
    • You can establish a reference to the pointer (int *&q=p, which gives the pointer p the alias Q),
1.2 References vs pointers
    • Cannot has NULL references, being able to assume (can be assumed) that a reference was connected to a legitimate piece of storage (a piece of legal inside Storage).
int &a;  // Error, reference can not be empty must has a reference to the object
    • Once a reference is initialized to an object, it cannot being changed to refer to another object. Pointers can pointed to another object at any time
 #include <iostream>using  namespace   STD;  int  Main (void   { int  a = 1     ;  int  b = 2     ;  int  & RA = A;  // int& ra = b;  //     Error, multiple initialization  return  0  ;}  
    • A reference must was initialized when it was created. Pointers can initialized at any time.
1.3 Reference Application
    • Reference parameter (the function parameter and argument are the same object)

You can modify the arguments while modifying the parameters.

There is no object replication and the object's overhead is avoided.

    • Common reference (const, avoids accidental modification of the function to the original argument)
    • Reference type return value

To return a reference from a function, make sure that the referenced target remains valid after the function is returned, that is, a reference to a local object in the body of the function that cannot be returned.

Local objects leave the scope and are destroyed, so you cannot return a reference to a local object in the body of the function.

1.passing parameters by references
#include <iostream>using namespacestd;voidSWAP1 (intAintb);voidSWAP2 (int*P1,int*p2);voidSWAP3 (int&a,int&b);intMain () {intNum1, num2; cout<<"Input integers:"; CIN>>num1>>num2;    Swap1 (NUM1, num2); cout<<num1<<" "<<num2<<Endl; cout<<"Input integers:"; CIN>>num1>>num2; SWAP2 (&AMP;NUM1, &num2);//the pointer is the address callcout<<num1<<" "<<num2<<Endl; cout<<"Input integers:"; CIN>>num1>>num2;    SWAP3 (NUM1, num2); cout<<num1<<" "<<num2<<Endl; return 0;}//passing parameter contents directlyvoidSWAP1 (intAintb) {    inttemp =A; A=b; b=temp;}//Passing PointersvoidSWAP2 (int*P1,int*p2) {    inttemp = *P1; *P1 = *P2; *P2 =temp;}//by referencevoidSWAP3 (int&a,int&AMP;B) {//function Parameters &    inttemp =A; A=b; b=temp;}
    • SWAP1 () directly passes the contents of the parameter and cannot achieve the purpose of exchanging a value of two digits. A, B is a formal parameter, the scope is limited to the internal function of the local variables, they have their own independent memory, and NUM1, num2 refers to the data is not the same.
    • SWAP2 () passes a pointer that is able to achieve the purpose of exchanging two-digit values. When the function is called, NUM1, num2 pointers are passed to P1, p2, then P1, P2 points to the data represented by a, B, and the values of A and B can be modified indirectly by pointers inside the function.
    • SWAP3 () is passed by reference and can achieve the purpose of exchanging a value of two digits. When the function is called, A and B are bound to the data referred to by NUM1, num2, and then A and NUM1, B and num2 all represent the same data, after modifying the data by a, it will affect the NUM1, and after modifying the data by B will also affect the num2.
2 Const Reference
#include <stdio.h>intMain () {intA = A; Const int&ra = A;//Const ReferenceA = the; //RA = 42; //error:the value of the target variable can is modified by a const referenceprintf"a=%d,ra=%d\n", A,ra); return 0;}
3. return by reference
int Task1 (intdouble y);    // uses return by value int& TASK2 (intdouble y);  // uses return by reference

Similar to passes by address (similar to delivery address), values returned by reference must is variables (you can not return a reference to a l Iteral or an expression (a literal or expression reference)). When a variable are returned by reference (return variables by reference), a reference to the variable is passed back to (passed to) the caller. The caller can then use this reference to continue modifying the variable.

However, just like return to address, you should not return local variables (local variable) by reference. Consider the following example:

int& doublevalue (int  x) {    int2;     return // return a reference to value here // value is destroyed here
#include <iostream>using namespacestd;

//Global Variableintnum;

//Function Declarationint&test ();intMain () {test ()=5; cout<<num; return 0;}int&Test () {returnnum;}

In program above, the return type of function test () is int&. Hence, this function returns a reference of the variable num.

The return statement is return num;. Unlike return by value, this statement doesn ' t return value of NUM, instead it returns the variable itself (address).

Important things to Remember when returning by Reference

    • Ordinary function returns value but this function doesn ' t. Hence, you cannot return a constant from the function.
int& Test () {    return2;}
    • You cannot return a local variable from the This function.
 int  & Test () { int  n = 2  ;  return   n;}  
#include <stdio.h>int; int& foo () {    return  Globalvar;} int Main () {    ten;   // Left value    printf ("Globalvar is:%d\n", Globalvar);     return 0 ;}
#include <iostream>using namespacestd;int& Squareref (int&);int* SQUAREPTR (int*);intMain () {intNumber1 =8; cout<<"In Main () &number1:"<< &number1 << Endl;//0x22ff14   int& result =Squareref (NUMBER1); cout<<"In Main () &result:"<< &result << Endl;//0x22ff14cout << result << Endl;// -cout << number1 << Endl;// -result = -;//adress, result aliascout << result << Endl;// -cout << number1 << Endl;// -   intNumber2 =9; cout<<"In Main () &number2:"<< &number2 << Endl;//0X22FF10   int* PResult = squareptr (&number2); cout<<"In Main () PResult:"<< PResult << Endl;//0X22FF10cout << *presult << Endl;//Bayicout << number2 << Endl;//Bayi}int& Squareref (int&Rnumber) {cout<<"In squareref ():"<< &rnumber << Endl;//0x22ff14Rnumber *=Rnumber; returnRnumber;}int* SQUAREPTR (int*Pnumber) {cout<<"In squareptr ():"<< Pnumber << Endl;//0X22FF10*pnumber *= *Pnumber; returnPnumber;}
1.4 Reference and Polymorphism

Reference is another means of (means) generating a polymorphic effect in addition to the pointer. This means, a reference to a base class can, and its derived (derived) class instance.

Reference of C + +

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.