|
|
 |
|
|
|
|
8: int intOne;
9: int &rSomeRef = intOne;
10:
11: intOne = 5;
12: cout << intOne: << intOne << endl;
13: cout << rSomeRef: << rSomeRef << endl;
14:
15: cout << &intOne: << &intOne << endl;
16: cout << &rSomeRef: << &rSomeRef << endl;
17:
18: return 0;
19: } |
|
|
|
|
|
|
|
|
intOne: 5
rSomeRef: 5
&intOne: 0x0012FF7C
&rSomeRef: 0x0012FF7C |
|
|
|
|
|
|
|
|
Analysis: Once again, rSomeRef is initialized as a reference to intOne. This time the addresses of the two variables are printed, and they are identical. C++ gives you no way to access the address of the reference itself because it is not meaningful, as it would be if you were using a pointer or other variable. References are initialized when created and always act as a synonym for their target, even when the address of operator is applied. |
|
|
|
|
|
|
|
|
For example, if you had a class called President, you might declare an instance of that class as follows: |
|
|
|
|
|
|
|
|
President William_Jefferson_Clinton; |
|
|
|
|
|
|
|
|
You might then declare a reference to President and initialize it with this object: |
|
|
|
|
|
|
|
|
President &Bill_Clinton = William_Jefferson_Clinton; |
|
|
|
|
|
|
|
|
There is only one President; both identifiers refer to the same object of the same class. Any action you take on Bill_Clinton will be taken on William_Jefferson_Clinton as well. |
|
|
|
|
|
|
|
|
Be careful to distinguish between the & symbol on line 9 of Listing 11.2, which declares a reference to int named rSomeRef, and the & symbols on lines 15 and 16, which return the addresses of the integer variable intOne and the reference rSomeRef. |
|
|
|
|
|
|
|
|
Normally, when you use a reference, you do not use the address of operator. You simply use the reference as you would use the target variable. This is shown on line 13. |
|
|
|
|
|