“引用”在C++(www.cppentry.com) 里是一个特殊的东西,其本意是“别名(alias)”。所有对“引用”的操作都会实施在“本尊”身上,“本尊”即被引用的对象—— 对“ 引用”取地址,实际取得的是“本尊”的地址;对“引用”取sizeof,实际取得的是“本尊”的大小。“引用”的特殊性还体现在很多地方,如只有数组的引用(reference toarray),但没有引用的数组(array of references);只有指针的引用(reference to pointer),没有指向引用的指针(pointer to reference),等等。引用的主要用途之一是用于函数(含操作符)的参数和返回类型,所以前
面这几章尚看不出其作用。
A reference serves as an alternative name for an object. In real-world programs, references are primarily used as formal parameters to functions. We’ll have more to say about reference parameters in Section 7.2.2 (p. 232). In this section we introduce and illustrate the use of references as independent objects.
A reference is a compound type that is defined by preceding a variable name by the & symbol. A compound type is a type that is defined in terms of another type. In the case of references, each reference type “refers to” some other type. We cannot define a reference to a reference type, but can make a reference to any other data type.
如果A 是一个类型,那么“复合类型”包括A*(指针)、A&(引用)、A[](数组)等。“引用”只有一层,不存在“二级引用”或“引用的引用”;相反,C++(www.cppentry.com) 里有“指向指针的指针”。
A reference must be initialized using an object of the same type as the reference:
- int ival = 1024;
- int &refVal = ival;
Because a reference is just another name for the object to which it is bound, all operations on a reference are actually operations on the underlying object to which the reference is bound:
adds 2 to ival, the object referred to by refVal. Similarly,
assigns to ii the value currently associated with ival.
When a reference is initialized, it remains bound to that object as long as the reference exists. There is no way to rebind a reference to a different object.
The important concept to understand is that a reference is just another name for an object. Effectively,we can access ival either through its actual name or through its alias, refVal. Assignment is just another operation, so that when we write
the effect is to change the value of ival to 5. A consequence of this rule is that you must initialize a reference when you define it; initialization is the only way to say to which object a reference refers.