引用变量

1.引用变量是已定义变量的别名,这点是与指针本质的区别

  int rats;

  int & rodents = rats;

  两者指向相同的值和内存单元

2.声明引用时必须进行初始化

  int rat;

  int & rodents;

  rodents = rats;

  这种是不被允许的

3.引用非常适合用于结构和类

案例分析:

1.交换

  void swap( int & a, int & b )

  {

    int temp = a;

    a = b;

    b = temp;

  }

  int a1 = 300;

  int a2 = 500;

  swap( a1, a2 );

     能够实现 a1  和  a2 的置换

2.返回指向结构的引用

  struct free

  {

    int made;

    int attempts;

  }

  free & accumulate( free & target, const free & source )

  {

    target.attempts += source.attempts;

    target.made += source.made;

    return target;

  }

  free team = { 10, 20 };

  free five = { 1, 1 };

  free dup;

  dup = accumulate( team, five );

  结果是dup和team都修改了,值变为11,21;

  注意:避免返回函数终止时不存在的变量,意味着不能返回函数内的局部变量

原文地址:https://www.cnblogs.com/penuel/p/11268876.html