A reference is an alias for another variable

2, read/write operations by reference are actually dependent on the way the original variable is referenced:

int x;
int & rx=x;
or
int x, &rx=x;
Copy the code

In C ampersand is the address. In C++ ampersand precedes the definition of a variable, which is a reference

Note:

This reference is an error; the referenced variable must be defined first

TIP:

C++ Pointers and reference symbols should be close to their type, not their name

Such as:

float* x;		//not: float *x;
int& y;			//not: int &y; This is a syntax error because the application must be attached to an object
Copy the code

Reference as function argument:

References can be used as function arguments, but only ordinary variables need to be passed when called.

When you change the value of a reference variable in a called function, you change the value of the argument

int main(a)
{
    int x = 0;
    int y{ 10 };
    int& rx = x;
    rx = 8;
    cout << x << endl;
     
    return 0;
}
Copy the code

Output: 8

int main(a)
{
    int x = 0;
    int y{ 10 };
    int& rx = x;
    rx = 8;

    const char* s = "Hello";
    const char* t = "World";

    const char*& r = s;     //r refers to s
    cout << r << endl;
     
    return 0;
}
Copy the code

Output: Hello!

When a reference variable is bound to a variable, its reference variable relationship cannot be changed

int main(a)
{
    int x = 0;
    int y{ 10 };
    int& rx = x;
    rx = 8;

    const char* s = "Hello";
    const char* t = "World";

    const char*& r = s;     //r refers to s. When a reference variable is bound to a variable, its reference variable relationship cannot be changed
    r = t;      //s=t; Place the first address of the World variable in r
    cout << r << endl;
    cout << s << endl;
    return 0;
}
Copy the code



Remember:

When we operate on a reference object, we are actually assigning to the object to which the reference is bound.

The reference itself holds the address of the referenced object.

Also: when encountering the & operator, how do you determine what it means

  1. with
  2. Take the address
  3. Define a reference type

Next to the right is the address (&x), next to the left is the reference (int&), hanging in the middle and the operation (a & b).

For deeper meanings and testing methods see: www.cnblogs.com/KaiMing-Pri… App.yinxiang.com/fx/c1155235…