【发布时间】:2020-10-25 04:54:53
【问题描述】:
当我尝试这段代码时 我得到的输出是
1 1 | 1 2
但是,如果我摆脱了引用,即
// replace
A& a_ref = b2;
a_ref = b1;
// with
b2 = b1;
输出变为
1 1 | 1 1
我找不到任何网站来解释为什么会发生这种情况。谁能解释一下?
#include <iostream>
struct A {
int foo;
};
struct B : public A {
int bar;
B(int x,int y) : bar(y) { this->foo=x; }
};
int main(void) {
B b1(1,1), b2(2,2);
A& a_ref = b2;
a_ref = b1;
std::cout << b1.foo << ' ' << b1.bar << " | " << b2.foo << ' ' <<
b2.bar << '\n';
return 0;
}
【问题讨论】:
-
您分配给
A的b2对象的子对象。b1隐式转换为A,因为左侧的类型是A。也就是说,赋值等价于a_ref = (A&)b1;。
标签: c++ inheritance struct