从Abstract Base Class访问另一个Base Classes成员

时间:2017-01-26 12:52:24

标签: c++

我想知道是否可以在类AbstractBase中声明纯虚函数并在Base中显示Derived类成员,因此它将使用Base的成员而不是在Derived中寻找实现。到目前为止,我试图通过尝试使用Base来使using的成员可视化但是它不会编译,因为在这种情况下,查找似乎忽略了使用。这有可能吗?这是我的代码:

#include <iostream>

using namespace std;

class AbstractBase {

public:
    AbstractBase(){}
    virtual ~AbstractBase(){}

protected:
    virtual void f() = 0;


};

class Base {

public:
    Base(){}

protected:
    void f() {cout << "called Base's f()" << endl;}

};

class Derived : public Base, public AbstractBase {

public:
    Derived(){}
    //using Base::f; /*this won't compile*/
private:
    void f(){} /*Access Base's f() here rather than implement*/


};

int main()
{
    Derived d;
}

2 个答案:

答案 0 :(得分:2)

使用::运算符:

class Derived : public Base {

public:
    Derived(){}
private:
    void f(){ Base::f() }  
};

此外,您无需继承AbstractBase

答案 1 :(得分:1)

在我看来,您希望f()是纯虚拟的,但提供默认实现。在这种情况下,可以通过这种方式实现:

#include <iostream>

using namespace std;

struct AbstractBaseWithDefaultF 
{
    virtual ~AbstractBaseWithDefaultF() = default;
    virtual void f() = 0;
};
void AbstractBaseWithDefaultF::f()
{
    cout << "called AbstractBaseWithDefaultF's f()" << endl;
}

struct Derived : AbstractBaseWithDefaultF
{
    void f() override 
    {
        AbstractBaseWithDefaultF::f();
        cout << "called Derived's f()" << endl;
    } 
};

int main()
{
    Derived d;
    d.f();
}

输出:

called AbstractBaseWithDefaultF's f()
called Derived's f()

这是live Wandbox example