阻止衍生類別重新定義虛函數, 在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!
注意: 私人繼承, 仍然可以繼續重新定義虛函數;
更多精彩內容:http://www.bianceng.cnhttp://www.bianceng.cn/Programming/cplus/
具體實現: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!
作者:csdn部落格 Spike_King