本文介绍了虚函数在私有或保护继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
很容易理解公共继承中的虚函数。
It's easy to understand the virtual function in public inheritance. So what's the point for virtual function in private or protected inheritance?
例如:
class Base {
public:
virtual void f() { cout<<"Base::f()"<<endl;}
};
class Derived: private Base {
public:
void f() { cout<<"Derived::f()"<<endl;}
};
这是否仍然称为覆盖?这种情况的用途是什么?这两个f()的关系是什么?
Is this still called overriding? What's the use of this case? What's the relationship of these two f()?
谢谢!
推荐答案
私有继承只是一种实现技术,不是一种关系,正如Scott Meyers在Effective C ++中所解释的:
Private inheritance is just an implementation technique, not an is-a relationship, as Scott Meyers explains in Effective C++:
class Timer {
public:
explicit Timer(int tickFrequency);
virtual void onTick() const; // automatically called for each tick
...
};
class Widget: private Timer {
private:
virtual void onTick() const; // look at Widget private data
...
};
小部件客户端不应该能够在Widget上调用onTick,因为这不是概念小部件界面。
Widget clients shouldn't be able to call onTick on a Widget, because that's not part of the conceptual Widget interface.
这篇关于虚函数在私有或保护继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!