钻石继承,c ++处理

时间:2016-05-24 14:28:53

标签: c++ inheritance multiple-inheritance virtual-inheritance diamond-problem

因此,我们有经典的钻石问题和int解决方案:

class A
{
public:
    A()
    {
        std::cout << "A c'tor" << std::endl;
    }
    void f()
    {
        std::cout << "A::f()" << std::endl;
    }
};

class B :virtual public A{};

class C :virtual public A{};

class D : public B, public C{};

编译器如何处理这个,所以它只创建一个A实例? 请尽可能详细地回答。

1 个答案:

答案 0 :(得分:2)

标准没有指定编译器应该如何处理,但通常(AFAIK gccMSVC),它按照我描述的方式实现下方。

当类继承通常时,它将包含所有基类成员

当类继承虚拟时,它将(而不是整个类)包含指向该基类所在位置的指针,虚拟基类应驻留在大多数派生对象中:

struct A
{
   int i;
};

struct B: virtual A{};

struct C: B{};



int someFunction()
{
    /* b internally contains pointer that points to it's (virtual)base class , 
    in this case B itself is most derived object so it points to base class
    which is stored somewhere inside B */

    B b;


    /* now subobject B (which is stored inside C) contains pointer that
      ,again points to it's (virtual) base class 
      ,but that class now resides in most derived object which is C */

    C c;
}

额外点:

你能弄明白错误在哪里吗?

struct A
{
    std::string message;

    A(std::string parameter): message(parameter) {}

};

struct B: virtual A
{
    B(std::string parameter): A(parameter) {}
};

struct C: B
{
    C(){}
};