为什么我可以为引用分配一个新值,以及如何使引用引用其他内容?
我有几个与在 C++ 中使用引用相关的问题.
I have couple of questions related to usage of references in C++.
在下面显示的代码中,它是如何工作的并且不会在
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 <<"
";
}
如何将引用 q 重新初始化为其他内容?
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) 它不能,您引用的行不会改变引用
-
- a) It cannot, the line you quote doesn't change the reference
q
, it changesp
. - 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 pointerp
point to something else.
- a) It cannot, the line you quote doesn't change the reference
你似乎认为这段代码
int i;
int &j = i;
int k;
j = k;
正在重新分配引用,但事实并非如此.它将k
的值赋值给i
,j
仍然指的是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.
相关文章