About References!

来源:互联网 发布:php前端和后端的区别 编辑:程序博客网 时间:2024/06/04 19:44
References

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 reference must be initialized using an object of the same type as the reference:

      int ival = 1024;      int &refVal = ival; // ok: refVal refers to ival      int &refVal2;       // error: a reference must be initialized      int &refVal3 = 10;  // error: initializer must be an object

A Reference Is an Alias

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:

      refVal += 2;

adds 2 to ival, the object referred to by refVal. Similarly,

      int ii = refVal;

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

      refVal = 5;

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.