引用是否可以在其生存期内引用多个对象

Can a reference refer to more than one object during its lifetime?

本文关键字:引用 对象 生存期 是否      更新时间:2023-10-16

据我所知,一个引用在其生命周期中只能引用一个对象。但是,下面的代码编译正确。虽然我已经更改了引用的对象..输出为:1.如何正确编译?

谢谢希兰

class A{
 private:
int a;
 public:
A(int a):a(a){}
virtual ~A(){}
virtual void f()const {cout<<a<<endl;}
};
class B: public A{
 private:
int b;
 public:
B(int Ina,int Inb):A(Ina),b(Inb){}
virtual void f()const {cout<<b<<endl;}
};
int main(){
    B b(1,2);
    A a(5);
    A& ref=a;
    ref=b;
    ref.f();
    return 0;
}

正确的思考方式是引用它引用的对象。因此,如果您这样做:

A& ref = a;
ref = b;

由于refa,您正在做的是:

a = b;

引用在其整个生命周期中仅引用一个引用。
代码的作用是将新值分配给原始引用方。

你的主函数等效于这个:

B b(1,2);
A a(5);
a = b;
a.f();
指派给

引用等效于指派给原始对象。