我们可以重新分配C ++中的引用吗? [英] Can we reassign the reference in C++?

查看:90
本文介绍了我们可以重新分配C ++中的引用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



为了测试我的理解,我写了一篇文章以下小程序。看来好像我已经成功地重新分配了一个引用。有人可以向我解释我的程序中实际发生了什么吗?

  #include< iostream> 
#include< stdio.h>
#include< conio.h>

using namespace std;

int main()
{
int i = 5,j = 9;

int& ri = i;
cout<< ri是:< ri <\ n;

i = 10;
cout<< ri是:< ri<< \\\
;

ri = j; //>>>>这不是重新分配参考? <<
cout<< ri是:< ri <\ n;

getch();
return 0;
}

代码编译正确,输出结果如下:

  ri is:5 
ri is:10
ri is:9


解决方案


ri = j; //>>>>这不是重新分配参考? <<


否, ri 仍然是对 i 的引用 - 您可以通过打印& ri

您所做的是修改 i 参考 ri



此外,如果您创建 c $ c> const int& cri = i; 它不会让你分配。


I have read everywhere that a reference has to be initialized then and there and can't be re-initialized again.

To test my understanding, I have written the following small program. It seems as if I have actually succeeded in reassigning a reference. Can someone explain to me what is actually going on in my program?

#include <iostream>
#include <stdio.h>
#include <conio.h>

using namespace std;

int main()
{
    int i = 5, j = 9;

    int &ri = i;
    cout << " ri is : " << ri  <<"\n";

    i = 10;
    cout << " ri is : " << ri  << "\n";

    ri = j; // >>> Is this not reassigning the reference? <<<
    cout << " ri is : " << ri  <<"\n";

    getch();
    return 0;
}

The code compiles fine and the output is as I expect:

ri is : 5
ri is : 10
ri is : 9

解决方案

ri = j; // >>> Is this not reassigning the reference? <<<

No, ri is still a reference to i - you can prove this by printing &ri and &i and seeing they're the same address.

What you did is modify i through the reference ri. Print i after, and you'll see this.

Also, for comparison, if you create a const int &cri = i; it won't let you assign to that.

这篇关于我们可以重新分配C ++中的引用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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