多重继承类引用 [英] Multiple Inheritance Class References

查看:215
本文介绍了多重继承类引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一对基类:

class A
{};

class B
{
    virtual void foo(A* ref);
    virtual void foo2(A* ref);
};

并且从他们,一些派生类:

And from them, a few derived classes:

class C : virtual public A
{
   int data;
};

class D : public B
{
    virtual void foo(A* ref)
    {
        ((C*) (ref)).data = 5;
    }
};

class E : virtual public A
{
    int otherData;
};

class F : public B
{
    virtual void foo2(A* ref)
    {
        ((E*) (ref)).otherData = 6;
    }
};

最后,我们有一个类似如下:

And finally, we have a class that follows suit, as such:

class G : public E, public C
{
};

,其主要功能如下:

int main()
{
   B* myD = new D();
   B* myF = new F();

   A* myA = new G();

   myD->foo(myA);
   myF->foo2(myA);

   return 0;
}

好吧,忽略一个明显的事实,这是一个可怕的钻石 ,由于 virtual )避免了多个As问题,一般的想法是我想让我的所有对象是Gs,Ds和Fs,但存储为引用As和Bs。我想能够使用B(实际上总是D或F)虚函数修改G的值...但是,A和B不知道任何他们的子类,因此不能被声明使用他们。这意味着虚函数参数必须总是一个指向A的指针。但是,D想让它的输入总是一个C,F想要它的输入是一个E.虽然这可能不是一个问题,如果G是继承自一个父母,我们当前的G继承自两个父母;我不知道这个指针如何实际工作在这样的情况下的底层上下文...但是,我不觉得这将是一个可能的情况。

Ok, IGNORING the obvious fact that this is a 'dreaded diamond' (which, the "multiple As" problem has been averted due to virtual), the general idea is that I want to have all my objects be Gs, Ds and Fs, but stored as references to As and Bs. I want to be able to use B's (which is actually always either D or F) virtual functions to modify the values of G... However, A and B do not know of any of their child classes, and thus cannot be declared using them. This means that the virtual function arguments must always be a pointer to an A. However, D wants to have it's input always be a C, and F wants it's input to be an E. While this might not have been an issue if G was inheriting from only one parent, our current G is inheriting from 2 parents; I do not know how the this pointers actually work in the underlying context of situations like this... however, I do not feel like this is going to be a possible situation.

任何人都愿意为投放指向父/子类的指针的机制提供一些光,如果有任何方式可以被拉掉? p>

Would anyone be willing to shed some light on the mechanisms of casting pointers to parent/child classes, and if there would be any way this could be pulled off?

推荐答案

假设您启用了RTTI,您可能会使用 dynamic_cast 将一个基类指针转换为派生(或同级)类指针。引用的对象在运行时测试,看它是否是一个兼容类,如果这不是一个有效的上传,它将返回0,在这种情况下你可以测试和分支。

Assuming you have RTTI switched on, which you most likely do, you can use dynamic_cast to attempt to up-cast a base class pointer to a derived (or sibling) class pointer. The referenced object is tested at runtime to see if it is a compatible class, if this is not a valid upcast than it will return 0, in which case you can test for that and branch.

http://en.wikipedia.org/wiki/Dynamic_cast

这篇关于多重继承类引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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