[英]Different results when I define references to same variable in different ways
I defined a class like this 我定义了这样的课程
class A
{
public:
A(int a, int b):a(a),b(b){}
void test(const char* name) {cout<<name<<": "<<a<<" "<<b<<endl;}
public:
int a,b;
};
then the main function: 然后主要功能:
int main()
{
A obj(1,2);
A& ref_1=obj;
A& ref_2=obj;
ref_1.a = 2;
ref_1.test("ref_1");
ref_2.test("ref_2");
cout<<&obj<<endl<<&ref_1<<endl<<&ref_2<<endl;
return 0;
}
the result, as I expect, is 如我所料,结果是
ref_1: 2 2
ref_2: 2 2
0x7fff59bb0c90
0x7fff59bb0c90
0x7fff59bb0c90
However, when I define two references like this: 但是,当我这样定义两个引用时:
A& ref_1=obj, ref_2=obj;
the result is very strange: 结果很奇怪:
ref_1: 2 2
ref_2: 1 2
0x7fff58a68c90
0x7fff58a68c90
0x7fff58a68c80
I use g++ as my compiler. 我使用g ++作为编译器。 Can anyone tell me why this thing happened? 谁能告诉我这件事为什么发生?
A& ref_1=obj, ref_2=obj;
is equivalent to 相当于
A& ref_1=obj;
A ref_2=obj;
If you want both to be references, you need to write 如果您想两者都作为参考,则需要编写
A &ref_1=obj, &ref_2=obj;
Alternatively, avoid this confusion altogether, and just write 或者,完全避免这种混乱,只写
A& ref_1=obj;
A& ref_2=obj;
like you did originally. 就像你原来那样。
When you write it as A& ref_1=obj, ref_2=obj;
当您将其写为A& ref_1=obj, ref_2=obj;
it's as if you wrote it as 就像你写的那样
A& ref_1=obj;
A ref_2=obj;
If you want to write it on one line and have both of them be references you'll need to write it as 如果您想将其写在一行上并且将它们都作为引用,则需要将其写为
A &ref_1=obj, &ref_2=obj;
You've fallen afoul of one of precedence. 您已经违反了优先顺序之一。
While what you've written reads as "declare ref_1 and ref_2 as type ref-to-A", the &
actually binds to the variable not the type. 虽然您写的内容为“将ref_1和ref_2声明为ref-to-A类型”,但&
实际绑定到变量而不是类型。 The same thing happens with pointers. 指针也会发生同样的事情。 This is why there is some ongoing debate about which is the more correct way to write references/pointers. 这就是为什么有人争论哪个是写引用/指针的更正确方法的原因。
A& ref_1; // ref_1 is a reference to type A.
A &ref_1; // means the same thing.
A& ref_1, ref_2;
A &ref_1, ref_2; // same as above.
A &ref_1, &ref_2; // what you thought the first line mean't
A* p1, p2; // p1 is a pointer, p2 is an instance of A
A *p1, *p2; // what you actually intended on the previous line.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.