C++中的引用变量是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2765999/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 00:38:13  来源:igfitidea点击:

What is a reference variable in C++?

c++referencevariables

提问by sirius79m

What would be a brief definition of a reference variable in C++?

C++ 中引用变量的简要定义是什么?

回答by CB Bailey

A referenceis an entity that is an alias for another object.

参考是对于另一个的别名的实体对象

A referenceis not a variableas a variableis only introduced by the declaration of an object. An objectis a region of storage and, in C++, references do not (necessarily) take up any storage.

参考不是变量作为变量仅由一个的声明引入对象。一个对象是存储的一个区域,并且在C ++中,引用不(一定)占用任何存储。

As objectsand referencesare distinct groups of entities in C++ so the term "reference variable" isn't meaningful.

由于对象引用是 C++ 中不同的实体组,因此术语“引用变量”没有意义。

回答by pankaj bhatt

A reference variable provides an alias (alternative name) for a previously defined variable. For example:

引用变量为先前定义的变量提供别名(替代名称)。例如:

float total=100;
float &sum = total;

It means both totaland sumare the same variables.

这意味着这两个totalsum是相同的变量。

cout<< total;
cout << sum;

Both are going to give the same value, 100. Here the &operator is not the address operator; float &means a reference to float.

两者都将给出相同的值,100。这里的&操作符不是地址操作符;float &表示对浮动的引用。

回答by Daniel Vassallo

The first paragraph of the Wikipedia articlecould easily serve as a brief definition:

维基百科文章的第一段可以很容易地作为一个简短的定义:

In the C++ programming language, a reference is a simple reference datatype that is less powerful but safer than the pointer type inherited from C.

在 C++ 编程语言中,引用是一种简单的引用数据类型,它比从 C 继承的指针类型功能更弱但更安全。

And quoting from the same article:

并引用同一篇文章:

C++ references differ from pointers in several essential ways:

  • It is not possible to refer directly to a reference object after it is defined; any occurrence of its name refers directly to the object it references.

  • Once a reference is created, it cannot be later made to reference another object; it cannot be reseated. This is often done with pointers.

  • References cannot be null, whereas pointers can; every reference refers to some object, although it may or may not be valid.

  • References cannot be uninitialized. Because it is impossible to reinitialize a reference, they must be initialized as soon as they are created. In particular, local and global variables must be initialized where they are defined, and references which are data members of class instances must be initialized in the initializer list of the class's constructor.

C++ 引用在几个基本方面与指针不同:

  • 引用对象被定义后是不可能直接引用的;任何出现的名称都直接引用它所引用的对象。

  • 一旦创建了一个引用,以后就不能再引用另一个对象;它不能重新安装。这通常是用指针完成的。

  • 引用不能为空,而指针可以;每个引用都指向某个对象,尽管它可能有效也可能无效。

  • 引用不能未初始化。因为不可能重新初始化引用,所以它们必须在创建后立即初始化。特别是,局部和全局变量必须在定义它们的地方初始化,作为类实例数据成员的引用必须在类的构造函数的初始化列表中初始化。

Further reading:

进一步阅读:

回答by Enrico Carlesso

It's a variable which referencesanother one:

这是一个引用另一个变量的变量:

int foo;
int& bar = foo;

baris now a reference, which is to say that barholds the location of memory where foolies.

bar现在是一个引用,也就是说bar保存内存所在的位置foo

See herefor more information.

请参阅此处了解更多信息。

回答by cammando

A Reference variableis an aliasfor the variable name.

参考变量是一个别名变量名

It is different from the pointers in following ways:

它在以下方面与指针不同:

  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 point to any another object whereas in case of pointer we can make it point to any other object at any time.
  3. A reference must be initialized the time it is created. Pointers can be made initialized at any time.
  1. 您不能有 NULL 引用。您必须始终能够假设引用已连接到合法的存储空间。
  2. 一旦引用被初始化为一个对象,就不能将其更改为指向任何其他对象,而在指针的情况下,我们可以随时使其指向任何其他对象。
  3. 必须在创建时初始化引用。可以随时初始化指针。

回答by Jonathan

Reference variables allow two variable names to address the same memory location:

引用变量允许两个变量名寻址相同的内存位置:

int main()
{
    int var1;

    // var2 is a reference variable, holds same value as var1

    int &var2 = var1;
    var1 = 10;

    std::cout << "var1 = " << var1 << std::endl;
    std::cout << "var2 = " << var2 << std::endl;
}

Resource: LINK

资源:链接

回答by Richard Chambers

A reference is an alternative label, an alias, for the object it is initialized with. Once a reference is initialized it can not be changed to be an alternative label or alias of some other object. After the initialization the reference or the object variable may be used interchangeably.

引用是一个替代标签,一个别名,用于初始化它的对象。一旦引用被初始化,就不能将其更改为某个其他对象的替代标签或别名。在初始化之后,引用或对象变量可以互换使用。

A reference has some of the characteristics of a const pointer to an object in that it is initialized when defined. And while what it references or points to can be changed, the reference or the const pointer itself can not be changed. However since a reference is an alternative label or alias it may or may not actually exist as a data object unlike a const pointer which will probably exist unless the compiler can optimize it away. And even if a reference is created as an actual entity by the compiler, that is compiler housekeeping and should be ignored since it officially does not exist much like the man behind the curtain in the Emerald City.

引用具有指向对象的 const 指针的一些特征,因为它在定义时被初始化。虽然它引用或指向的内容可以更改,但引用或 const 指针本身不能更改。然而,由于引用是一个替代标签或别名,它实际上可能会或可能不会作为数据对象存在,这与 const 指针不同,除非编译器可以优化它,否则它可能会存在。即使编译器将引用创建为实际实体,这也是编译器的内务管理,应该被忽略,因为它正式不像翡翠城幕后的人那样存在。

The following code samples gives examples comparing and contrasting reference with pointer and const pointer:

以下代码示例给出了将引用与指针和常量指针进行比较和对比的示例:

int myInt;           // create a variable of type int, value not initialized
int myInt2 = 3;      // create a second variable of type int with a value of 3
int &rInt = myInt;   // create a reference to the variable of type int, myInt

rInt = 5;            // myInt now has a value of 5, the reference is an alias for myInt
rInt++;              // myInt now has a value of 6, the reference is an alias for myInt
rInt = myInt2;       // myInt now has the same value as myInt2, a value of 3
int *pInt = &rInt;   // pInt points to myInt
(*pInt)++;           // increments myInt
pInt++;              // increments the pointer which formerly pointed to myInt

int &rInt2;          // error C2530: 'rInt2' : references must be initialized
int *pInt2;          // just fine, uninitialized pointer is ok
int * const pInt3;   // error C2734: 'pInt3' : const object must be initialized if not extern
int * const pInt4 = &myInt;  // define and initialize const pointer
pInt4 = &myInt2;     //  error C3892: 'pInt4' : you cannot assign to a variable that is const

There are actually two kinds of references: an lvaluereference and an rvaluereference.

实际上有两种引用:lvalue引用和rvalue引用。

An lvaluereference is the same reference in the C++ language before C++11. An rvaluereference was introduced in C++11 to allow for a reference to a temporary object to assist with doing a move rather than a copy and some other actions where a copy is the wrong approach but a move is the right approach.

lvalue引用与 C++11 之前的 C++ 语言中的引用相同。一个rvalue参考C ++ 11引入允许对临时对象的引用,以帮助那里的副本是错误的做法,但此举是正确的做法做一个举动,而不是一个副本和其他一些行动。

For example a comparison of lvalue reference and rvalue reference in the following simple source lines. Because these are intreferences that means that an assignment of a non-integer value results in the compiler doing a conversion which results in a temporary variable. An rvaluereference can bind to a temporary variable and an lvaluereference can not.

例如,以下简单源代码行中左值引用和右值引用的比较。因为这些是int引用,这意味着对非整数值的赋值会导致编译器进行转换,从而产生临时变量。一个rvalue参考可以绑定到一个临时变量和lvalue参考不能。

// assign a double to an int causing creation of temporary    
int &rIntd1 = 1.2;   // error C2440: 'initializing' : cannot convert from 'double' to 'int &'
int &&rIntd2 = 1.2;  // warning C4244: 'initializing' : conversion from 'double' to 'int', possible loss of data

rInt = rIntd2;       // myInt from the code above now has a value of 1, 1.2 was truncated when converting from double to int

回答by Spectral

A reference variableand a pointer variableare the exact same thing to the machine (the compiler will generate the same machine code).

引用变量和一个指针变量是完全相同的事情到机器(编译器将产生相同的机器代码)。

The most obvious advantages of using a reference variable over a pointer variable in my knowledge:

据我所知,使用引用变量而不是指针变量的最明显优势:

  1. Easy to understand(no address, de-reference all kinds of headache things)
  2. Saves you a tiny bit of typing, adn thus probably less error-prone.
  1. 易于理解(无地址,去参考各种头痛的事情)
  2. 为您节省一点打字时间,因此可能不太容易出错

In the code below, the left side is using a reference variable, and the right side is using a pointer variable. They are the same thing to the machine, but you see the using reference variable saves you a little bit of typing.

在下面的代码中,左侧使用的是引用变量,右侧使用的是指针变量。它们对机器来说是一样的,但是您会看到 using 引用变量为您节省了一点打字时间。

Reference variable           Pointer variable
int a = 1;         ~~~~~~    int a = 1;
int &b = a;        ~~~~~~    int *b = &a;
b = 2;             ~~~~~~    *b = 2;
cout << a << '\n'  ~~~~~~    cout << a << '\n'
==============================================
2                  ~~~~~~    2

回答by Bishwas Pokharel

Reference variables (let a), just say for easy understanding, another name of variable (let x), which holds the same exact memory location as that of x.

引用变量(let a),简单说一下,变量(let x)的另一个名称,与 的内存位置完全相同x

int &a = x;refers that a holds same memory location as that of x.

int &a = x;指的是 a 拥有与 相同的内存位置x

For example, say two roommates share the same room. One friends name is xand another friends name is a. If achanges the location of the table placed in the room, from position (x,y,z)to (x1,y1,z1)then changes are visible to friend xas well and vice versa.

例如,假设两个室友共用一个房间。一个朋友的名字是x,另一个朋友的名字是a。如果a更改放置在房间中的桌子的位置,则从位置(x,y,z)(x1,y1,z1)然后更改对朋友也是可见的,x反之亦然。