C++ 为什么我可以为引用分配一个新值,以及如何使引用引用其他内容?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7181372/
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 16:33:59  来源:igfitidea点击:

Why can I assign a new value to a reference, and how can I make a reference refer to something else?

c++reference

提问by goldenmean

I have couple of questions related to usage of references in C++.

我有几个与 C++ 中引用的使用相关的问题。

  1. In the code shown below, how does it work and not give a error at line q = "world";?

    #include <iostream>
    
    using namespace std;
    
    int main()
    {
      char *p = "Hello";
      char* &q = p;
      cout <<p <<' '<<q <<"\n";
      q = "World"; //Why is there no error on this line
      cout <<p <<' '<<q <<"\n";
    }
    
    1. How can a reference q be reinitialized to something else?

    2. Isn't the string literal, p = "Hello", a constant or in read-only space? So if we do,

      q = "World";
      

      wouldn't the string at pwhich is supposed to be constant be changed?

  2. I have read about C++ reference type variables as they cannot be reinitialized or reassigned, since they are stored 'internally' as constant pointers. So a compiler would give a error.

    But how actually a reference variable can be reassigned?

    int i;
    
    int &j = i;
    
    int k;
    
    j = k; //This should be fine, but how we reassign to something else to make compiler flag an error?
    

    I am trying to get hold of this reference, and in that maybe missed some key things related, so these questions.

  1. 在下面显示的代码中,它是如何工作的并且不会在第 1 行出现错误q = "world";

    #include <iostream>
    
    using namespace std;
    
    int main()
    {
      char *p = "Hello";
      char* &q = p;
      cout <<p <<' '<<q <<"\n";
      q = "World"; //Why is there no error on this line
      cout <<p <<' '<<q <<"\n";
    }
    
    1. 如何将引用 q 重新初始化为其他内容?

    2. 字符串文字, p = "Hello", 不是常量或只读空间吗?所以如果我们这样做,

      q = "World";
      

      p应该是常量的字符串不会改变吗?

  2. 我已经阅读了 C++ 引用类型变量,因为它们无法重新初始化或重新分配,因为它们在“内部”存储为常量指针。所以编译器会报错。

    但实际上如何重新分配引用变量?

    int i;
    
    int &j = i;
    
    int k;
    
    j = k; //This should be fine, but how we reassign to something else to make compiler flag an error?
    

    我正在尝试获取此参考资料,并且可能错过了一些相关的关键内容,所以这些问题。

So any pointers to clear this up, would be useful.

因此,任何清除此问题的指针都会很有用。

回答by john

    • a) It cannot, the line you quote doesn't change the reference q, it changes p.
    • b) No the literal is constant, but pis a pointer which points at a literal. The pointer can be changed, what is being pointed to cannot. q = "world";makes the pointer ppoint to something else.
  1. You seem to think that this code

    int i;
    int &j = i;
    int k;
    j = k;
    

    is reassigning a reference, but it isn't. It's assigning the value of kto i, jstill refers to i. I would guess that this is your major misunderstanding.

    • a)它不能,您引用的行不会改变引用q,它会改变p
    • b) 不是文字是常量,而是p指向文字的指针。指针可以改变,所指向的不能。 q = "world";使指针p指向别的东西。
  1. 你似乎认为这段代码

    int i;
    int &j = i;
    int k;
    j = k;
    

    正在重新分配参考,但事实并非如此。它正在分配kto的值ij仍然指的是i。我猜这是你的主要误解。

回答by templatetypedef

An important detail about references that I think you're missing is that once the reference is bound to an object, you can never reassign it. From that point forward, any time you use the reference, it's indistinguishable from using the object it refers to. As an example, in your first piece of code, when you write

我认为您缺少的关于引用的一个重要细节是,一旦引用绑定到一个对象,您就永远无法重新分配它。从那时起,无论何时使用引用,它都与使用它引用的对象没有区别。例如,在您的第一段代码中,当您编写

q = "World";

Since qis a reference bound to p, this is equivalent to writing

由于q是一个绑定到 的引用p,这相当于写

p = "World";

Which just changes where pis pointing, not the contents of the string it's pointing at. (This also explains why it doesn't crash!)

这只是改变p指向的位置,而不是它指向的字符串的内容。(这也解释了为什么它不会崩溃!)

As for your second question, references cannot be reassigned once bound to an object. If you need to have a reference that can change its referent, you should be using a pointer instead.

至于你的第二个问题,一旦绑定到一个对象,就不能重新分配引用。如果您需要一个可以更改其所指对象的引用,则应改用指针。

Hope this helps!

希望这可以帮助!

回答by Alok Save

a) How can a reference q be reinitialized to something else?

a) 如何将引用 q 重新初始化为其他内容?

It cannot be!

它不可能是!

An reference variable remains an alias to which it was initialized at time of creation.

引用变量仍然是它在创建时初始化的别名。



b)Isn't the string literal, p = "Hello", a constant/in read only space. So if we do,
No it doesn't.

b) 不是字符串文字 p = "Hello",常量/只读空间。所以如果我们这样做,
不,它不会。

char* &q = p;

Here qis an reference to pointer of the type char p. The string here is constant put the pointer is not, it can be pointed to another string, and the reference is alias to this pointer not the string literal so it is valid.

q是对 char 类型的指针的引用p。这里的字符串是常量,指针不是,它可以指向另一个字符串,并且引用是这个指针的别名而不是字符串文字,所以它是有效的。



c) Second question I have is I have read about C++ reference type variables as they cannot be reinitialized/reassigned, since they are stored 'internally' as constant pointers. So a compiler would give a error.

c) 我的第二个问题是我已经阅读了 C++ 引用类型变量,因为它们无法重新初始化/重新分配,因为它们在“内部”存储为常量指针。所以编译器会报错。

int i;

int &j = i;

int k;

j = k; //This should be fine, but how we reassign to something else to make compiler flag an error

Does not reassign the reference. it changes the value of the variable to which it was alias.

不重新分配引用。它改变了它作为别名的变量的值。

In this case it changes the value of ito k

在这种情况下,它将的值更改ik

回答by jmishra

Treat reference as an alias name and I hope the world of reference will much easier to understand.

将引用视为别名,我希望引用的世界会更容易理解。

int p; // Declares p as an integer; Defines p & allocates space
int &q = p ; // Declares a Reference. Though they are symbolically 2 variables,
             // they essentially refer to same name and same memory location.

So, p = 5 and q = 5 will be all the same.

所以,p = 5 和 q = 5 都是一样的。

In your example,

在你的例子中,

char *p = "Hello"; // Declares your pointer to "Hello". p has its own existence.
char* &q = p;  // This now creates a reference (alias) to p with name q.

So all in all, p & q are names of the entity/object (memory).

总而言之, p & q 是实体/对象(内存)的名称。

So, if you assign q something, it reflects in p too. Coz it is same as the assignment to p. So q = "World", means p too now points to "World". i.e. the Memory location which p & q both refer to - holds the address of first character of "World".

所以,如果你给 q 赋值,它也会反映在 p 中。因为它与对 p 的赋值相同。所以 q = "World",意味着 p 现在也指向 "World"。即 p & q 所指的内存位置 - 保存“世界”的第一个字符的地址。

I hope the second question need not be answered if you understand the notion of reference as an alias.

如果您将引用的概念理解为别名,我希望第二个问题不需要回答。