C ++ reference notes
1. What is reference:
Explanation in Baidu Encyclopedia: Reference is an alias of a variable (target). The operations on reference are exactly the same as those on variables. Expressed with & Symbol
Example:
1 using namespace std; 2 int _ tmain (int argc, _ TCHAR * argv []) 3 {4 int love = 520; 5 int & ai = love; 6/* ai is the alias of the integer variable love. The actual operation on ai is the operation on love. 7. Note that the Ampersand in front of ai are not the address operators. Here they are the symbols of the quote operators 8. same but different functions 9 */10 cout <"ai: "<ai <endl; // the actual operation is on the love variable, so the ai value is 52011 ai = 0; 12 cout <" love: "<love <endl; // the value of love in the previous line of ai = 0 is also changed to 013 cin. get (); 14 return 0; 15}
The above code is slightly changed to distinguish:
1 # include <iostream> 2 using namespace std; 3 int _ tmain (int argc, _ TCHAR * argv []) 4 {5 int love = 520; 6 int & ai = love; 7 8 cout <"love address:" <& love <endl; // get the love variable address 9 cout <"ai address:" <& ai <endl; // obtain the alias ai address 10 cin. get (); 11 return 0; 12}
We can see that the memory addresses are the same, so that we can understand that the alias is referenced, and the alias operation is the original name operation.
2. reference object:
1 # include <iostream> 2 using namespace std; 3 class myCls // define class 4 {5 public: 6 int AddNum (int x, int y) 7 {8 return x + y; 9} 10 11}; 12 int _ tmain (int argc, _ TCHAR * argv []) 13 {14 myCls Love; // first create an object Love15 myCls & rlove = Love; // define the object love alias as rlove16 // myCls & rmyCls = myCls; error: we cannot define the alias 17 int sum = rlove for the class. addNum (2, 3); // After definition, you can call the data member in the class to access 18 cout <sum <endl; 19 cin. get (); 20 return 0; 21}