1
2
| int nValue = 5; // normal integer int &rnRef = nValue; // reference to nValue |
1
2
3
4
5
6
| nValue = 6; // nValue is now 6 rnRef = 7; // nValue is now 7 cout << nValue; // prints 7 nValue++; cout << rnRef; // prints 8 |
1
2
| cout << &nValue; // prints 0012FF7C cout << &rnRef; // prints 0012FF7C |
1
2
3
4
| int nValue = 5; int &rnRef = nValue; // valid reference int &rnInvalidRef; // invalid, needs to reference something |
1
2
3
4
5
| int nValue = 5; int nValue2 = 6; int &rnRef = nValue; rnRef = nValue2; // assigns value 6 to nValue -- does NOT change the reference! |
1
2
3
4
| int nValue = 5; const int &rnRef = nValue; rnRef = 6; // illegal -- rnRef is const |
1
| const int &rnRef = 6; |
1
2
3
4
5
6
7
8
9
10
11
12
13
| struct Something { int nValue; float fValue; }; struct Other { Something sSomething; int nOtherValue; }; Other sOther; |
sOther.sSomething.nValue
. If there are many separate accesses to this member, the code can become messy. References allow you to more easily access the member:
1
2
| int &rnValue = sOther.sSomething.nValue; // rnValue can now be used in place of sOther.sSomething.nValue |
1
| sOther.sSomething.nValue = 5; |
1
| rnValue = 5; |
0 comments: