当我以不同方式定义对同一变量的引用时,结果不同

Different results when I define references to same variable in different ways

本文关键字:引用 结果 变量 方式 定义      更新时间:2023-10-16

我定义了这样的类

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;
};

然后主函数:

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;
}

我期望的结果是

ref_1: 2  2
ref_2: 2  2
0x7fff59bb0c90
0x7fff59bb0c90
0x7fff59bb0c90

但是,当我定义两个参考时:

    A& ref_1=obj, ref_2=obj;

结果非常奇怪:

ref_1: 2  2
ref_2: 1  2
0x7fff58a68c90
0x7fff58a68c90
0x7fff58a68c80

我将G 用作编译器。谁能告诉我为什么这件事会发生?

A& ref_1=obj, ref_2=obj;

等于

A& ref_1=obj;
A ref_2=obj;

如果您希望两者都是参考,则需要写

A &ref_1=obj, &ref_2=obj;

另外,完全避免这种混乱,然后写

A& ref_1=obj;
A& ref_2=obj;

就像您最初的一样。

当您以 A& ref_1=obj, ref_2=obj;的形式编写它时,就好像您以

的形式写了
A& ref_1=obj;
A ref_2=obj;

如果您想在一行上写下它,并且两个是参考文献,则需要将其写为

A &ref_1=obj, &ref_2=obj;

您已经陷入了先例之一。

当您所写的内容读为" ref_1 and ref_2为ref-to-a"时,&实际上绑定到变量而不是类型。指针也发生了同样的事情。这就是为什么关于哪种更正确的撰写参考/指针的方式进行的持续辩论。

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.