我们可以重新分配C ++中的引用吗? [英] Can we reassign the reference in 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; //>>>>这不是重新分配参考? <<
否, 您所做的是修改 此外,如果您创建 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? The code compiles fine and the output is as I expect:
No, What you did is modify Also, for comparison, if you create a 这篇关于我们可以重新分配C ++中的引用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! ri
仍然是对 i
的引用 - 您可以通过打印& ri
和
i
参考 ri
。
c $ c> const int& cri = i;
它不会让你分配。#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;
}
ri is : 5
ri is : 10
ri is : 9
ri = j; // >>> Is this not reassigning the reference? <<<
ri
is still a reference to i
- you can prove this by printing &ri
and &i
and seeing they're the same address.i
through the reference ri
. Print i
after, and you'll see this.const int &cri = i;
it won't let you assign to that.