Learning notes of C + +


Quotation: it is a kind of rhetorical device, which refers to the words of famous people, or the things, things, poems, allusions, fables, idioms, proverbs, proverbs, etc. of famous people to support the author’s position, so as to prove and strengthen his theory and enrich the content of the article [1].

In C + +, reference is another name for an existing object. For example, one of your friends, Xiao Ming, sometimes you call him dog egg, sometimes you call him Henti, sometimes you call him Dad. Xiao Ming has always been Xiao Ming, but our name for him has changed. That’s what quotation means.
(the reference variable is an alias)
(the reference variable does not allocate independent memory space, it shares its memory space with the target variable)

I often call Xiaoming an old dog and call him to play games. Every time he runs fast, after all, it’s good to recognize his name.
(once the reference is successful, you can use the reference name or variable name to point to the variable.)

Of course, when you give Xiao Ming a nickname, you must have a friend who can afford it, or you are making something out of nothing… Do something you don’t agree with.
(there is no null reference, the reference must be connected to a legal memory)

To avoid confusion“commonly”I won’t use the nicknames I gave Xiao Ming. (PS: unless someone points a gun at me and says “long live the pointer”), after all, he is my Xiao Ming~
When a reference is initialized as one object, it cannot be pointed to another object,A pointer can point to another object at any time
(in particular, if the reference is used as a function parameter or return value, the initial value may not be provided.)

If I give Xiao Ming a nickname, I must be very positive. I will give him one at the first time. Of course, if the strange man who shouts long live the pointer comes again, I will listen to him anytime, anywhere.
(references must be initialized at creation time. The pointer can be initialized at any time.)

int i = 1024;
int &r = i;

double s = 4201;
double &d= s;

The first declaration reads: “R is an integer reference initialized to I.”
The second declaration reads as: “D is a double reference initialized to s.”

As a parameter
When a reference is used as a parameter in a function, it can play the role of “changing the incoming value”, which is bidirectional.

As the return value

double A[] = { 1.2, 2.3 , 4.5 , 6.7}
double &B(int i)
    return vals[i];
int main()
    B(2) = 9.8; // The value of a [2] is changed to 9.8 instead of 4.5
    B(0) = 0.3;// The value of a [0] is changed to 0.3 instead of 1.2