阻止派生類重新定義虛函數, 在java和C#中可以很簡單的實現(finale&sealed),
但在C++中則需要使用public繼承+復合(composition)的方法;
注意: 使用私有繼承(private), 無法實現此要求.
如:
/*************************************************
File: test.cpp
Copyright: C.L.Wang
Author: C.L.Wang
Date: 2014-04-11
Description: test
Email: morndragon@126.com
**************************************************/
/*eclipse cdt, gcc 4.8.1*/
#include <iostream>
using namespace std;
class Timer {
public:
virtual void onTick() const {
std::cout << "Tick! Tick! Tick! " << std::endl;
}
};
class Widget : private Timer {
public:
void say() {
onTick();
}
private:
virtual void onTick() const override{
std::cout << "Widget Tick!" << std::endl;
}
};
class AnotherWidget : private Widget {
public:
void say() {
onTick();
}
private:
virtual void onTick() const override{
std::cout << "Another Widget Tick!" << std::endl;
}
};
int main () {
Widget w;
w.say();
AnotherWidget aw;
aw.say();
return 0;
}
輸出:
Widget Tick! Another Widget Tick!
注意: 私有繼承, 仍然可以繼續重新定義虛函數;