为什么我可以为引用分配一个新值,以及如何使引用引用其他内容? [英] Why can I assign a new value to a reference, and how can I make a reference refer to something else?

查看:13
本文介绍了为什么我可以为引用分配一个新值,以及如何使引用引用其他内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

#include <iostream>

using namespace std;

int main()
{
  char *p = "Hello";
  char* &q = p;
  cout <<p <<' '<<q <<"
";
  q = "World"; //Why is there no error on this line
  cout <<p <<' '<<q <<"
";
}

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

  1. How can a reference q be reinitialized to something else?

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

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

q = "World";

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

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

  • 我读过 C++ 引用类型变量,因为它们无法重新初始化或重新分配,因为它们在内部"存储为常量指针.所以编译器会报错.

  • 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.

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

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

    推荐答案

      • a) 它不能,您引用的行不会改变引用 q,它会改变 p.
      • b) 不,文字是常量,但 p 是指向文字的指针.指针可以改变,指向的东西不能.q = "world"; 使指针 p 指向别的东西.
      • a) It cannot, the line you quote doesn't change the reference q, it changes p.
      • b) No the literal is constant, but p is a pointer which points at a literal. The pointer can be changed, what is being pointed to cannot. q = "world"; makes the pointer p point to something else.

    你似乎认为这段代码

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

    正在重新分配引用,但事实并非如此.它将k 的值赋值给ij 仍然指的是i.我猜这是你的主要误解.

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

    这篇关于为什么我可以为引用分配一个新值,以及如何使引用引用其他内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    相关文章
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆