【cmu15445c++入门】c++引用

发布时间:2024年01月06日

引用

引用是一个别名,这个别名在内存中引用相同的数据。引用在追踪数据、传递参数、性能提升很有用。

代码

// A reference in C++ is a method of creating an alias to a variable, where
// these aliases refer to the same data in memory. References are useful for
// keeping track of state, passing arguments into functions, and for general
// performance improvements. In general, it is important to understand
// references to do well in this class.
//引用是一个别名,这个别名在内存中引用相同的数据。引用在追踪数据、传递参数、性能提升很有用。

// Includes std::cout (printing) for demo purposes.
#include <iostream>

// A function that takes an int reference and adds 3 to it.
void add_three(int &a) { a = a + 3; }

int main() {
  // Take this expression. Note that b has type int& (int reference),
  // since it is a reference to a. This means that a and b both refer to the
  // same data. You can declare references by setting your variables type via
  // the single ampersand syntax.
  int a = 10;
  int &b = a;// b的类型是  int&, 是a的引用,可以通过&符号设置引用。

  // As stated, if we try to print b, we will get 10.
  std::cout << "b is " << b << std::endl;// 输出b is 10

  // References can also be passed into functions. Take the function add_three,
  // which takes in an int reference and adds 3 to it. If we call this function,
  // on a, since a is being taken as a reference, then a's value in the caller
  // context will change value.

  //引用也可以传递到函数中。以函数 add_three 为例,它接受一个 int 引用并向其添加 3。
  //如果我们在 a 上调用这个函数,由于 a 被作为引用,那么 a 在调用者上下文中的值将改变值。
  
  add_three(a);
  std::cout << "a is " << a << std::endl;// 输出a is 13
  
  std::cout << "b is " << b << std::endl;// 输出b is 13

  return 0;
}

运行?

文章来源:https://blog.csdn.net/Kangyucheng/article/details/135430127
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。