2.3 Compound Types (2)

2013-10-07 16:15:42 · 作者: · 浏览: 70

Reference Definitions

We can define multiple references in a single definition. Each identifier that is a referencemust be preceded by the & symbol:

  1. int i = 1024, i2 = 2048; // i and i2 are both ints   
  2. int &r = i, r2 = i2; // r is a reference bound to i; r2 is an int   
  3. int i3 = 1024, &ri = i3; // i3 is an int; ri is a reference bound to i3   
  4. int &r3 = i3, &r4 = i2; // both r3 and r4 are references 

With two exceptions that we’ll cover in § 2.4.1 (p. 61) and § 15.2.3 (p. 601), the type of a reference and the object to which the reference refersmust match exactly. Moreover, for reasons we’ll explore in § 2.4.1, a referencemay be bound only to an object, not to a literal or to the result of a more general expression:

  1. int &refVal4 = 10; // error: initializer must be an object   
  2. double dval = 3.14;   
  3. int &refVal5 = dval; // error: initializer must be an int object