具有相同名称的抽象和已定义继承函数的多重继承

编程入门 行业动态 更新时间:2024-10-24 22:22:05
本文介绍了具有相同名称的抽象和已定义继承函数的多重继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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.

更多推荐

具有相同名称的抽象和已定义继承函数的多重继承

本文发布于:2023-11-05 19:11:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1561621.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:抽象   函数   定义   名称

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!