【发布时间】:2013-09-10 20:08:54
【问题描述】:
这是我的问题:
#include <iostream>
using namespace std;
class A {
public:
virtual void f() = 0;
};
class B {
public:
void f() {cout << "Hello world!" << endl;};
};
class C : public A, private B {
public:
using B::f; // I want to use B::f as my implementation of A::f
};
int main() {
C c; // error: C is abstract because f is pure virtual
c.f();
}
到目前为止,我找到了两种解决方法:
在类 C 中定义一个函数 f,它只调用 B::f。但这很乏味而且不那么干净(尤其是在为一堆函数这样做时)
B 继承自 A,C 继承自 B(全部公开)。对我来说,它不能很好地代表设计。特别是,B 不是 A,我不希望 B 依赖 A。
你还能想到其他的可能性吗?
【问题讨论】:
-
如果
B不是A,为什么还要实现A::f? -
我不明白为什么
using B::f;没有void f() { B::f(); }那么乏味。如果是我,无论如何我都不会为这两个函数使用相同的名称,而是B::f_impl。 -
恕我直言,如果 2 个类 A 和 B 有一个同名的方法(我猜同名 f(),意味着相同或相似的目的),它们可能应该有一个共同的基础。一般来说,如果您在实现与继承相关的内容时遇到困难,您应该考虑查看架构。
-
@Angew 那么,
template<class... Args> auto f(Args&&... args) -> decltype(B::f(std::forward<Args>(args)...)) { /*..*/ }
标签: c++ c++11 multiple-inheritance