引用是一个别名,这个别名在内存中引用相同的数据。引用在追踪数据、传递参数、性能提升很有用。
// 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;
}