Reference (lvalue reference)

  Reference

  A reference is not an object. Instead, a reference is just another name for an already existing object.
                             ----《C++ Primer英文版第五版》
  引用必需被初始化。
  引用的类型与引用相关连对象的类型必须一致。
  引用只能绑定到对象,不能绑定到字面量或表达式的结果上。
  int  ival = 100;
  int &refVal = ival; // refVal refers to (is another name for) ival
  int &refVal2;       // error: a reference must be initialized(引用必需被初始化)
  int &refVal3 = 10;  // error: initializer must be an object(初始化列表必需是对象)
  double pi = 3.14;
  int &refVal4 = pi;  // error: initializermust be an int object(类型不一致)

  Because references are not objects, we may not define a reference to a reference.
                             ----《C++ Primer英文版第五版》
  int &refVal5 = refVal; // ok: refVal5 is bound to the object to which refVal is bound,
              // i.e., to ival
                 // refVal5是ival的引用,而不是refVal的引用,因为引用不是对象,
              // 又只能用对象初始化
  int i = refVal;     // ok: initializes i from the value in the object to which
              // refVal is bound
               // i.e., initializes i to the same value as ival


  Reference to const(待续。。。)
  

猜你喜欢

转载自blog.csdn.net/linuxwuj/article/details/10427601
今日推荐