作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我的理解是,在 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;
}
最佳答案
让我们看看你的类结构,如果你创建一个 E
的实例,您最终会得到一个如下所示的对象层次结构:
class B class A class B
\ / \ /
\ / \ /
\ / \ /
class C class D
\ /
\ /
\ /
class E
您会看到 B
有两个实例, 但只有一个 A
的实例.这是因为虚拟继承。两者 C
和 D
继承自 A
使用虚拟继承,所以只有一个 A
的实例在你的e
.
现在让我们看看用户代码:
E e;
C &c = e; // reference C in the object hierarchy of E
D &d = e; // reference D in the object hierarchy of E
c.set_n(3); // set the value in the only instance of A in E
d.set_c('b'); // set the value of one of the two instances of B in your e
std::cout << c.get_c(); // print the value in the other instance of B in e
// not the one you set before
std::cout << d.get_n(); // print the value of the only instance of A in e
// this got changed before
关于c++ - 输出变为 a2a3 而不是 a2b3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14623655/
我是一名优秀的程序员,十分优秀!