引用是否可以在其生存期内引用多个对象
Can a reference refer to more than one object during its lifetime?
据我所知,一个引用在其生命周期中只能引用一个对象。但是,下面的代码编译正确。虽然我已经更改了引用的对象..输出为: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;
由于ref
是a
,您正在做的是:
a = b;
引用在其整个生命周期中仅引用一个引用。
代码的作用是将新值分配给原始引用方。
你的主函数等效于这个:
B b(1,2);
A a(5);
a = b;
a.f();
指派给引用等效于指派给原始对象。
相关文章:
- 引用对象成员函数的成员函数
- 从 Base 引用对象调用派生类的成员
- 转换引用对象的边界框?
- 现代编译器会优化只引用对象子集的局部变量吗
- l值引用对象上的Constexpr成员函数:Clang和gcc不同意
- 将 const 类型引用对象注册为类成员对象C++
- Boost Intervocess:通过迭代通过从结构引用对象的映射进行迭代时
- 无法用2D矢量成员引用对象
- 在由引用对象传递中访问由引用对象传递的变量
- 如何使用QString引用对象名称
- 使用自动迭代器引用对象
- C++ 在另一个对象中引用对象的当前状态
- 使用共享对象和引用对象进行引用计数
- 未显式引用对象的全局对象构造函数在最终二进制文件 - LD 中被丢弃
- 引用对象的动态类型何时可以更改
- 引用对象内部的指针
- C++从全局静态函数中引用对象
- C++如何仅在没有其他人直接或间接引用对象指针时删除该指针
- 如何使用C++引用对象
- 为什么引用对象仅保存特定类型的引用