我想知道是否可以在类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;
}
答案 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()