可以为间接基类共享基类的实例吗? [英] Share instance of base class for indirect base classes possible?

查看:57
本文介绍了可以为间接基类共享基类的实例吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须承认我在提出这个问题时遇到了麻烦,但我会尽力而为.我试图寻找问题的答案,但我怀疑我找不到所需的内容,因为我不确定该怎么称呼.

I must admit I'm having trouble formulating this question, but I'll try my best to be precise. I have tried to search for an answer to my question, but I suspect I have been unable to find what I'm looking for, as I'm not exactly sure what to call this.

我有一个基类A,还有几个从该基类继承的子类.然后,我使另一个类X继承自某些提到的子类.我现在面临的问题是,每个X继承的类都有各自的类A实例.下面的代码应更好地理解我的意思.

I have a base class A, and several child classes inheriting from this base class. I then make another class X that inherits from some of the mentioned child classes. The problem I'm now facing is that each of the classes X inherits, have their own instance of class A. The code below should give a better understanding of what I mean.

class A;
class B : public A;
class C : public A;

class X : public B, public C;

当它们都充当同一类的间接基类时,是否有办法使B类和C类共享A类的相同实例?

Is there a way to make class B and C share the same instance of class A, when they are both acting as indirect base classes for the same class?

举一个为什么我想要这样做的例子,让我们看一下这段代码.

To give an example of why I want this, lets look at this code.

    class A
    {
        int _x;
    };

    class B : public A
    {
        void outputX(){std::cout << A::_x << std::endl;
    };

    class C : public A
    {
       void setX(int x){A::_x=x;}
    };

    class X : public B, public C
    {
        C::setX(5);

        // this will output an un-initialized _x, 
        // as B and C have their own version of A
        B::outputX() 
    };

现在我意识到在此示例中这似乎没有必要,但是在我的实际情况下,我想如果B和C在类X中共享A的实例将是一个很好的解决方案.

Now I realize this seems rather unnecessary in this example here, but in my real situation I like to think it would be a good solution if B and C shared instance of A in class X.

这有可能吗?

推荐答案

您可以通过使用虚拟继承来解决此问题:

You can solve this by using virtual inheritance:

class B : virtual public A;
class C : virtual public A;

class X : virtual public B, virtual public C;

有关钻石问题的更多信息.

这篇关于可以为间接基类共享基类的实例吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆