参考自Dan Saks的文章
The key insights
I believe the key insight into why C++ has reference types as well as pointer types is that reference types enable overloaded operators to look like built-in operators, as well as act like them.
Pointers can do almost everything that references can do, but they can lead to expressions that don't look right. On the other hand, references have some restrictions that make them less convenient than pointers for implementing algorithms and data structures. References reduce, but do not eliminate, the need for pointers.
As a general rule, use references in function parameters and return types to define attractive interfaces. Use pointers to implement algorithms and data structures.
Samples:
1) int *x[n] //[] has higher precedence than*.
It means that x is an "array withN elements of type pointer"
2) char *f(int) //() has the same precedence as [].
It means that f is a function returning a pointer to achar.
3) char (*f)(int)
It means that f is a pointer to a function returning achar.
4) char &g(int)
It means that g is a function returning a reference to achar.
5) char (&g)(int)
It means that g is a reference to a function returning a char.
6) const int &ri = i is equivalent toint const &ri = i
因为reference天生就是const所以只有指向常量的引用而没有常量引用的说法。
int &const rj = j; // error
7) int const *p = &i //pointer toconst
8) int *const q = &j //const pointer
假设有对象定义:
MyObjectType obj1;
1. 值传递:
如果函数定义为:
void myFunction( MyObjectType obj);
函数调用:
myFunction(obj); //函数以外对象obj的值不会 改变
2. reference传递:
如果函数定义为:
void myFunction( MyObjectType &obj);
函数调用:
myFunction(obj); //函数以外对象obj的值会 改变
3. 指针传递:
如果函数定义为:
void myFunction( MyObjectType *obj);
函数调用:
myFunction(&obj); //需要dereference(&), 函数以外对象obj的值会 改变