Cplusplus 简明教程

C++ References

引用变量是一个别名,即已存在变量的另一个名称。一旦引用使用变量进行初始化,变量名称或引用名称都可以用来引用变量。

A reference variable is an alias, that is, another name for an already existing variable. Once a reference is initialized with a variable, either the variable name or the reference name may be used to refer to the variable.

References vs Pointers

引用通常与指针混淆,但引用和指针之间的三个主要区别是 -

References are often confused with pointers but three major differences between references and pointers are −

  1. You cannot have NULL references. You must always be able to assume that a reference is connected to a legitimate piece of storage.

  2. Once a reference is initialized to an object, it cannot be changed to refer to another object. Pointers can be pointed to another object at any time.

  3. A reference must be initialized when it is created. Pointers can be initialized at any time.

Creating References in C++

将变量名视为连接到变量在内存中的位置的标签。然后,您可以将引用视为连接到该内存位置的第二个标签。因此,您可以通过原始变量名或引用访问变量的内容。例如,假设我们有以下示例 -

Think of a variable name as a label attached to the variable’s location in memory. You can then think of a reference as a second label attached to that memory location. Therefore, you can access the contents of the variable through either the original variable name or the reference. For example, suppose we have the following example −

int i = 17;

我们可以为 i 声明引用变量,如下所示。

We can declare reference variables for i as follows.

int& r = i;

在这些声明中读取 & 作为 reference 。因此,将第一个声明读取为“r 是初始化为 i 的整数引用”,将第二个声明读取为“s 是初始化为 d 的双精度引用”。以下示例使用 int 和 double 的引用 -

Read the & in these declarations as reference. Thus, read the first declaration as "r is an integer reference initialized to i" and read the second declaration as "s is a double reference initialized to d.". Following example makes use of references on int and double −

#include <iostream>

using namespace std;

int main () {
   // declare simple variables
   int    i;
   double d;

   // declare reference variables
   int&    r = i;
   double& s = d;

   i = 5;
   cout << "Value of i : " << i << endl;
   cout << "Value of i reference : " << r  << endl;

   d = 11.7;
   cout << "Value of d : " << d << endl;
   cout << "Value of d reference : " << s  << endl;

   return 0;
}

当上述代码被编译并执行后,它会产生以下结果 -

When the above code is compiled together and executed, it produces the following result −

Value of i : 5
Value of i reference : 5
Value of d : 11.7
Value of d reference : 11.7

引用通常用于函数参数列表和函数返回值。因此,以下是 C 程序员应清楚的两个与 C 引用相关的重要主题 -

References are usually used for function argument lists and function return values. So following are two important subjects related to C references which should be clear to a C programmer −

Sr.No

Concept & Description

1

References as ParametersC++ supports passing references as function parameter more safely than parameters.

2

Reference as Return ValueYou can return reference from a C++ function like any other data type.