当前位置:天才代写 > tutorial > C语言/C++ 教程 > C++:阻止派生类(derived class)从头界说虚函数(finalsealed)

C++:阻止派生类(derived class)从头界说虚函数(finalsealed)

2017-11-02 08:00 星期四 所属: C语言/C++ 教程 浏览:711

阻止派生类从头界说虚函数, 在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!

作者:csdn博客 Spike_King

 

    关键字:

天才代写-代写联系方式