【问题标题】:Multiple inheritance: using a member function of a private base [duplicate]多重继承:使用私有基的成员函数[重复]
【发布时间】: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(); 
}

到目前为止,我找到了两种解决方法:

  1. 在类 C 中定义一个函数 f,它只调用 B::f。但这很乏味而且不那么干净(尤其是在为一堆函数这样做时)

  2. B 继承自 A,C 继承自 B(全部公开)。对我来说,它不能很好地代表设计。特别是,B 不是 A,我不希望 B 依赖 A。

你还能想到其他的可能性吗?

【问题讨论】:

  • 如果B不是A,为什么还要实现A::f?
  • 它被称为using declaration
  • 我不明白为什么using B::f; 没有void f() { B::f(); } 那么乏味。如果是我,无论如何我都不会为这两个函数使用相同的名称,而是 B::f_impl。
  • 恕我直言,如果 2 个类 A 和 B 有一个同名的方法(我猜同名 f(),意味着相同或相似的目的),它们可能应该有一个共同的基础。一般来说,如果您在实现与继承相关的内容时遇到困难,您应该考虑查看架构。
  • @Angew 那么,template&lt;class... Args&gt; auto f(Args&amp;&amp;... args) -&gt; decltype(B::f(std::forward&lt;Args&gt;(args)...)) { /*..*/ }

标签: c++ c++11 multiple-inheritance


【解决方案1】:

using 声明是将B::f 函数添加到类作用域中以进行查找,但该函数仍然是B::f,而不是C::f。您可以在派生类型中定义实现并转发到B::f 实现,否则您必须更改继承层次结构,以便B 和C 都(实际上)从A 继承。

void C::f() { B::f(); }   // simple forwarding implementation

【讨论】:

    猜你喜欢
    • 2015-01-21
    • 1970-01-01
    • 2013-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-15
    • 2013-06-20
    相关资源
    最近更新 更多