具有相同名称的抽象和已定义继承函数的多重继承 [英] Multiple Inheritance with abstract and defined inherited functions of the same name

查看:101
本文介绍了具有相同名称的抽象和已定义继承函数的多重继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我很抱歉是否还有其他帖子可以回答这个问题,我发现所有类似的帖子都涉及菱形继承方案或定义的函数,而事实并非如此.

First off I apologize if there is another post out there that answers this, all the similar posts I found dealt with diamond inheritance schemes or defined functions, which this does not.

简而言之,我想知道是否有可能让一个类从另外两个类继承而来,其中两个子类都具有一个具有相同名称和参数的函数,但它是在一个子类中定义的,并且在其他.此外,如果我能做到这一点,那么在对纯虚拟/抽象类进行调用的函数中,如果对派生类所做的更改很少,最终会在另一个子类上调用已定义的函数呢?

In short, I'm wondering if it is possible to have one class inherit from two other classes where both child classes has a function with the same name and arguments but it is defined in one child class, and pure-virtual in another. Furthermore if I can do this, would invoking the function on the pure-virtual/abstract class end up calling the defined function on the other child class with minimal changes to the derived class?

示例:

class A
{
    public:
    virtual void Set(int X) = 0;
};

class B
{
    public:
    virtual void Set(int X);
};

class AB : public A, public B
{
    //other methods not relevant to example go here
};

int main(int argc, char **argv)
{
    int Y = 5;
    A* ObjectA = new AB();
    ObjectA->Set(Y);
    return 0;
}

到目前为止,我尝试编译此基本示例的尝试都遇到了以下错误:

So far my attempts to compile this basic example have been met with errors that say:

'AB':无法实例化抽象类 由于以下成员: 'void A :: Set(int)':是抽象的

'AB' : cannot instantiate abstract class due to following members: 'void A::Set(int)' : is abstract

进行自己的研究时,找不到明确的答案,但是基于其他与相关主题相关的问题,我发现在AB类中使用使用B :: Set"可能会有所帮助.但是,当我尝试将其添加到AB类定义中时,错误仍然存​​在.

When doing my own research I couldn't find a clear answer, but based on other questions that dealt with related topics I found that using a "using B::Set" in class AB may help with this. But when I try adding it to the AB class definition, the error persists.

有什么办法可以使这项工作完成?

Is there any way I can make this work?

推荐答案

您是否尝试过实现该方法:

Have you tried implementing the method:

class AB : public A, public B
{
    void Set(int X) {}
};

不起作用的原因是A::Set()是纯虚拟的. IE.它没有实现.但是您尝试调用它.您必须在派生类中重写它才能实例化派生类.

The reason it's not working is that A::Set() is pure virtual. I.e. it has no implementation. But you try to call it. You have to override it in the derived class in order to be able to instantiate the derived class.

using在您的情况下不起作用,因为您有一个A*,因此编译器没有歧义.

The using doesn't work in your case because you have an A*, so there's no ambiguity for the compiler.

如果您有:

AB* ObjectA = new AB();
ObjectA->Set(Y);

您必须在AB声明中使用using来解决歧义.

you'd have to use using inside the declaration of AB to resolve the ambiguity.

这篇关于具有相同名称的抽象和已定义继承函数的多重继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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