我了解的是,在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

08-25 08:13