阻止派生类重新定义虚函数, 在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!
注意: 私有继承, 仍然可以继续重新定义虚函数;
具体实现:public继承+复合的方式, 代码实现, 如下:
/************************************************* 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() { timer.onTick(); } private: class WidgetTimer : public Timer { public: virtual void onTick() const { std::cout << "Widget Tick! " << std::endl; } }; WidgetTimer timer; }; int main () { Widget w; w.say(); return 0; }
输出:
Widget Tick!