Using reference) and pointers can indirectly access another value, but there are two important differences between them.
1. Reference always points to an object: it is wrong to define the reference without initialization.
2. Differences in Value assignment: assigning a value to a reference modifies the value of the object associated with the reference, rather than associating the reference with another object. Once the reference is initialized, it always points to the same specific object, which is why the reference must be initialized at the definition ).
The following two differences are illustrated:
Example 1:
#include <iostream>using namespace std;void main() { int ival = 1024, ival2 = 2048; int *pi = &ival, *pi2 = &ival2; pi = pi2; cout<<ival<<" "<<ival2<<endl; cout<<pi<<" "<<pi2<<endl;}
After the assignment, the value of the ival object pointed to by pi is 1024 and remains unchanged. The assignment operation modifies the value of the pi pointer so that it points to another object, pi and pi2 point to the same address!
Example 2:
#include <iostream>using namespace std;void main() { int ival = 1024, ival2 = 2048; int &ri = ival, &ri2 = ival2; ri = ri2; // assigns ival2 to ival cout<<ival<<" "<<ival2<<endl; cout<<&ri<<" "<<&ri2<<endl;}
This assignment operation modifies the ival object referenced by ri, not the reference itself. After the value assignment, the value of ival is the same as that of ival2, Which is 2048, but the two references still point to the original associated object ri and ri2 addresses respectively). At this time, the values of these two objects are equal.
This article is from my study notes blog, please be sure to keep this source http://6924918.blog.51cto.com/6914918/1270676