gpt4 book ai didi

c++ - 输出变为 a2a3 而不是 a2b3

转载 作者:行者123 更新时间:2023-11-30 02:01:01 25 4
gpt4 key购买 nike

我的理解是,在 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 的实例.这是因为虚拟继承。两者 CD继承自 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com