C++使用接口基本實(shí)現(xiàn)方式解析
C++編程語(yǔ)言的應(yīng)用對(duì)于開發(fā)人員來(lái)說(shuō)是一個(gè)非常有用的應(yīng)用語(yǔ)言。不過(guò)其中還有許多比較高深的內(nèi)容值得我們?nèi)セù罅康臅r(shí)間去學(xué)習(xí)。在這里就先為大家介紹一下有關(guān)C++使用接口的實(shí)現(xiàn)方法。
面向?qū)ο蟮恼Z(yǔ)言諸如JAVA提供了Interface來(lái)實(shí)現(xiàn)接口,但C++卻沒(méi)有這樣一個(gè)東西,盡管C++ 通過(guò)純虛基類實(shí)現(xiàn)接口,譬如COM的C++實(shí)現(xiàn)就是通過(guò)純虛基類實(shí)現(xiàn)的(當(dāng)然MFC的COM實(shí)現(xiàn)用了嵌套類),但我們更愿意看到一個(gè)諸如 Interface的東西。下面就介紹一種解決辦法。
首先我們需要一些宏:
- //
- // Interfaces.h
- //
- #define Interface class
- #define DeclareInterface(name) Interface name { \
- public: \
- virtual ~name() {}
- #define DeclareBasedInterface(name, base) class name :
- public base { \
- public: \
- virtual ~name() {}
- #define EndInterface };
- #define implements public
有了這些宏,我們就可以這樣定義我們的接口了:
- //
- // IBar.h
- //
- DeclareInterface(IBar)
- virtual int GetBarData() const = 0;
- virtual void SetBarData(int nData) = 0;
- EndInterface
是不是很像MFC消息映射那些宏啊,熟悉MFC的朋友一定不陌生?,F(xiàn)在我們可以像下面這樣來(lái)實(shí)現(xiàn)C++使用接口這一功能:
- //
- // Foo.h
- //
- #include "BasicFoo.h"
- #include "IBar.h"
- class Foo : public BasicFoo, implements IBar
- {
- // Construction & Destruction
- public:
- Foo(int x) : BasicFoo(x)
- {
- }
- ~Foo();
- // IBar implementation
- public:
- virtual int GetBarData() const
- {
- // add your code here
- }
- virtual void SetBarData(int nData)
- {
- // add your code here
- }
- };
怎么樣,很簡(jiǎn)單吧,并不需要做很多的努力我們就可以實(shí)現(xiàn)C++使用接口這一操作了。
【編輯推薦】