同样,一个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; |
注意指针解引用必须括在括号,因为成员选择运算符具有比解引用操作符的优先级更高的。
因为访问结构和类成员通过指针是笨拙的语法,C + +提供的第二个成员选择运算符(->)从指针做成员选择。下面的两行是等价的: