[英]Access another Base Classes member from Abstract Base Class
I wonder if it is possible to declare a pure virtual function in class AbstractBase
and make a Base
classes member visible in Derived
so it will use the member of Base
and not look for a implementation in Derived
. 我想知道是否有可能在类AbstractBase
声明一个纯虚函数并使Derived
的Base
类成员可见,因此它将使用Base
的成员而不在Derived
查找实现。 So far, i tried making Base
's member visual by trying to use using
but it won't compile since the look up, in this case, seems to ignore using. 到目前为止,我尝试通过尝试使用using
来使Base
的成员可视化但是它不会编译,因为查找,在这种情况下,似乎忽略使用。 Is this possible at all? 这有可能吗? Here is my code: 这是我的代码:
#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;
}
Use ::
operator: 使用::
运算符:
class Derived : public Base {
public:
Derived(){}
private:
void f(){ Base::f() }
};
Also, you don't need to inherit from AbstractBase
. 此外,您不需要从AbstractBase
继承。
It looks to me that you would like f()
to be pure-virtual but provide default implementation. 在我看来,您希望f()
是纯虚拟的,但提供默认实现。 In this case, it can be achieved this way: 在这种情况下,可以通过这种方式实现:
#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();
}
Output: 输出:
called AbstractBaseWithDefaultF's f()
called Derived's f()
Here's a live Wandbox example . 这是一个实时的Wandbox示例 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.