【发布时间】:2012-07-26 05:26:09
【问题描述】:
是否有可能有多个抽象接口的部分实现,然后收集这些部分实现到一个单个具体类通过使用多重继承?
我有以下示例代码:
#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;
}
编译失败,出现以下错误:
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()
【问题讨论】:
-
+1 表示简短、独立的示例。
-
"抽象接口" 概括地说:抽象接口意味着虚拟继承(特殊情况可能不同)
-
"
struct D1 : Base" 你在这里使用公共继承是有原因的吗?客户端代码是否对D1感兴趣? -
@curiousguy 没有理由 - 只是举了一个例子 - 在我的特殊用途中,我根据情况混合使用公共和私人
标签: c++ multiple-inheritance virtual-inheritance