从抽象基类的多个部分实现继承?

编程入门 行业动态 更新时间:2024-10-25 00:28:03
本文介绍了从抽象基类的多个部分实现继承?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

可以有一些抽象接口的部分实现,然后收集这些部分实现到单个具体类通过使用多重继承?

Is it possible to have a number of partial implementations of an abstract interface, and then collect these partial implementations into a single concrete class by using multiple inheritence?

我有以下示例代码:

#include <iostream> struct Base { virtual void F1() = 0; virtual void F2() = 0; }; struct D1 : Base { void F1() override { std::cout << __func__ << std::endl; } }; struct D2 : Base { void F2() override { std::cout << __func__ << std::endl; } }; // collection of the two partial implementations to form the concrete implementation struct Deriv : D1, D2 { using D1::F1; // I added these using clauses when it first didn't compile - they don't help using D2::F2; }; int main() { Deriv d; return 0; }

无法编译时出现以下错误:

This fails to compile with the following errors:

main.cpp: In function ‘int main()’: main.cpp:27:11: error: cannot declare variable ‘d’ to be of abstract type ‘Deriv’ main.cpp:19:8: note: because the following virtual functions are pure within ‘Deriv’: main.cpp:5:18: note: virtual void Base::F1() main.cpp:6:18: note: virtual void Base::F2()

推荐答案

尝试从 Base :

struct D1 : virtual Base { void F1() override { std::cout << __func__ << std::endl; } }; struct D2 : virtual Base { void F2() override { std::cout << __func__ << std::endl; } };

没有虚拟继承,你的多继承场景看起来像是继承自两个单独的和不完整的基类 D1 和 D2 ,两者都不能实例化。

Without the virtual inheritance, your multiple inheritance scenario looks like inheritance from two separate and incomplete base classes D1 and D2, neither of which can be instantiated.

更多推荐

从抽象基类的多个部分实现继承?

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

发布评论

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

>www.elefans.com

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