我的理解是,在 E 对象中,C 和 D 对象分别由 c 和 d 引用。但我无法理解为什么 d.set_c('b') 无法将 B.m_c 初始化为 'b',因为 c.set_n(3) 能够将 A.m_n 的值更改为 3。
#include <iostream>
class A
{
public:
A(int n = 2) : m_n(n) {}
public:
int get_n() const { return m_n; }
void set_n(int n) { m_n = n; }
private:
int m_n;
};
class B
{
public:
B(char c = 'a') : m_c(c) {}
public:
char get_c() const { return m_c; }
void set_c(char c) { m_c = c; }
private:
char m_c;
};
class C
: virtual public A
, public B
{ };
class D
: virtual public A
, public B
{ };
class E
: public C
, public D
{ };
int main()
{
E e; //object of E is created
C &c = e; //c is used to refrence C object in E Object
D &d = e; //c and d has same inheritance structure
std::cout << c.get_c() << d.get_n();
c.set_n(3);
d.set_c('b');
std::cout << c.get_c() << d.get_n() << std::endl;
return 0;
}