C++ reference

1. Definition

    First of all, we have to understand the three conditions of indirect assignment:

    1. Define two variables (one actual parameter and one formal parameter).

    2. To establish an association, the actual parameter takes the address to the formal parameter.

    3. Indirectly modify the value of the actual parameter through the formal parameter.

    The essence of reference is to alias the same memory space, and reference is to help us simplify the last two conditions of indirect assignment.

2. Use

    1. Often quoted

         For example: int a;const int &Ra = a;

                   Ra = 1; //error

                    a = 1; //correct

        Ra is often quoted as readable but not writable.

        Two initialization methods that are often cited:

                     int x = 30; const int &y = x; initialize constant reference with variable

                    const int a = 30;const int &b = a ;initialize const reference with literal

       2. Reference as return value

           E.g:

            int &fuction (int *p)

             {
         *p = 10;
           return *p;
               }
               int main()
               {
             int a=4;
             int *p=&a;
               fuction(p);
                }

            3. Reference as parameter

                int fuction (int &p)
                {
             p =3;
            return p;
                 }
                int main()
                {
                 int a=4;
                  fuction(a);
                }

! Welcome to point out the shortcomings

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326645229&siteId=291194637