简体   繁体   English

c ++多重继承

[英]c++ multiple inheritance

I cannot figure out what would happen in the following scenario: 我无法弄清楚在以下场景中会发生什么:

class MBase {
    public:
       MBase(int) {}
       virtual char* vf() const = 0;
       virtual ~MBase() {}
};

class D1 : public MBase { //NOT VIRTUAL!!!
   public:
   D1() : MBase(1) {}
   char* vf() const { return "D1"; }
};

class D2 : virtual public MBase {
    public:
        D2() : MBase(2) {}
        char* vf() const { return "D2"; }
};

class Bottom : public D1, public D2 {
  public:
    char* vf() const { return "Bottom"; }
}

Base* b = new Bottom();  

In the original definition of the diamond both D1 and D2 were inheriting virtually from MBase, but here only one is. 在钻石的原始定义中,D1和D2几乎都是从MBase继承的,但这里只有一个。 Would we still have two separate subobjects in Bottom object and therefore, the last line will not compile as compiler won't know which subobject to use? 我们在Bottom对象中是否还有两个独立的子对象,因此,最后一行不会编译,因为编译器不知道要使用哪个子对象?

This is specified in section 10.1.4 of the C++03 standard. 这在C ++ 03标准的10.1.4节中规定。 Virtual and non-virtual bases are independent, so there will be one of each. 虚拟和非虚拟基础是独立的,因此每个基础中都有一个。

It is easy to see this by expanding your example: 通过扩展您的示例很容易看到这一点:

class MBase {
    public:
       MBase(int arg) { cerr << "MBase::MBase(" << arg << ")\n"; }
       virtual const char* vf() const = 0;
       virtual ~MBase() {}
};

class D1 : public MBase { //NOT VIRTUAL!!!
   public:
   D1() : MBase(1) {}
   const char* vf() const { return "D1"; }
};

class D2 : virtual public MBase {
    public:
        D2() 
        : MBase(2) // This doesn't get used in this example because
                   // it is the responsibility of the most-derived
                   // class to initialize a virtual base, and D2 isn't
                   // the most-derived class in this example.
        {
        }
        const char* vf() const { return "D2"; }
};

class Bottom : public D1, public D2 {
  public:
    Bottom() 
    : MBase(5) // D1 and D2 default constructors are called implicitly.
    { 
    }
    const char* vf() const { return "Bottom"; }
};

int main(int argc,char **argv)
{
  Bottom b;
  return 0;
}

Outputs: 输出:

MBase::MBase(5)
MBase::MBase(1)

I think you problem is similar to this one... Basically, each objet has their own base object of mBase class... 我认为你的问题类似于这个......基本上,每个objet都有自己的mBase类基础对象......

Diamond inheritance 钻石继承

Regards, Erwald 此致,Erwald

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM