首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >c++多重继承

c++多重继承
EN

Stack Overflow用户
提问于 2012-04-15 00:56:18
回答 2查看 111关注 0票数 1

我不知道在下面的场景中会发生什么:

代码语言:javascript
复制
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();  

在钻石的原始定义中,D1和D2实际上都是从MBase继承的,但这里只有一个是继承的。我们是否仍然会在底层对象中有两个单独的子对象,因此,最后一行将不会编译,因为编译器不知道使用哪个子对象?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-04-15 01:04:22

这是在C++03标准的第10.1.4节中指定的。虚拟基础和非虚拟基础是独立的,因此每个基础都会有一个。

通过扩展示例可以很容易地看到这一点:

代码语言:javascript
复制
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;
}

输出:

代码语言:javascript
复制
MBase::MBase(5)
MBase::MBase(1)
票数 2
EN

Stack Overflow用户

发布于 2012-04-15 01:05:22

我想你的问题和这个类似...基本上,每个对象都有自己的mBase类的基对象...

Diamond inheritance

向您致敬,Erwald

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10155473

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档