C++ 输出是a2a3而不是a2b3
我所理解的是,在E对象中,C和D对象分别由C和D引用。但我无法理解为什么d.set_c'b'无法将b.m_c初始化为'b',而as c.set_n3可以将A.m_n的值更改为3C++ 输出是a2a3而不是a2b3,c++,multiple-inheritance,C++,Multiple Inheritance,我所理解的是,在E对象中,C和D对象分别由C和D引用。但我无法理解为什么d.set_c'b'无法将b.m_c初始化为'b',而as c.set_n3可以将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
#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;
}
改变
到
以获得输出a2b3
在您的示例中,E实例包含多个单独的B实例。更改
, public B
到
以获得输出a2b3
在您的示例中,E实例包含多个单独的B实例。让我们看看您的类结构,如果创建E实例,您将得到如下所示的对象层次结构:
class B class A class B
\ / \ /
\ / \ /
\ / \ /
class C class D
\ /
\ /
\ /
class E
您可以看到有两个B实例,但只有一个A实例。这是因为虚拟继承。C和D都使用虚拟继承从A继承,因此e中只有一个A实例
现在让我们看看用户代码:
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
让我们看看您的类结构,如果您创建一个E实例,您将得到如下所示的对象层次结构:
class B class A class B
\ / \ /
\ / \ /
\ / \ /
class C class D
\ /
\ /
\ /
class E
您可以看到有两个B实例,但只有一个A实例。这是因为虚拟继承。C和D都使用虚拟继承从A继承,因此e中只有一个A实例
现在让我们看看用户代码:
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
类E的对象包含C和D子对象,而C和D子对象又各自包含一个B子对象。因为没有关于B的虚拟继承,所以C和D中的每一个都包含它们自己的B副本
d、 set_c然后引用d中包含的B并更新它,而c.get_c引用c中包含的B,它独立于d中的B,因此没有更改
对于类A及其成员n,不存在此类问题,因为使用了虚拟继承。这确保了在E类的最后一个对象中,每个人都只使用一个子对象A,无论通过哪个路径访问它。E类的对象包含C和D子对象,而C和D子对象又分别包含B子对象。因为没有关于B的虚拟继承,所以C和D中的每一个都包含它们自己的B副本
d、 set_c然后引用d中包含的B并更新它,而c.get_c引用c中包含的B,它独立于d中的B,因此没有更改
对于类A及其成员n,不存在此类问题,因为使用了虚拟继承。这确保在E类的最终对象中,每个人都使用一个子对象A,不管它是通过哪个路径访问的。< /P>请选择一个更有用的标题吗?请你选择一个更有用的标题吗?我已经编程C++两年了,从来没有想过这个问题。先生,你应该得到一次投票和一次感谢。谢谢。我已经编程C++两年了,从来没有想过这个问题。先生,你应该得到一次投票和一次感谢。非常感谢。