引用和指针
引用和指针引用的行为像一个const指针解引用一个有趣的关系式。从而给出如下:
1
2
3
|
int
nValue = 5; int
* const
pnValue = &nValue; int
&rnValue = nValue; |
1
2
|
*pnValue
= 6; rnValue
= 6; |
同样,一个const引用的行为就像一个const指针指向const对象是隐式解引用。
因为引用总是“点”来有效的对象,而不能指出释放内存,引用的是比使用指针安全。如果一个任务可以通过引用或指针解决,参考一般应首选。指针通常只能用在引用是不充分的情况下(如动态分配的内存)。
成员的选择
通常有一个指针或引用一个结构(或类)。正如你已知道的,你可以选择使用一个struct的成员选择运算符成员(。):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
struct
Something { int
nValue; float
fValue; }; //
Member selection using actual struct variable Something
sSomething; sSomething.nValue
= 5; //
Member selection using reference to struct Something
&rsSomething = sSomething; rsSomething.nValue
= 5; //
Member selection using pointer to struct Something
*psSomething = &sSomething; (*psSomething).nValue
= 5; |