龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > 软件开发 > C/C++开发 >

C++使用接口基本实现方式解析

时间:2011-04-12 23:18来源:未知 作者:admin 点击:
分享到:
C++ 编程语言的应用对于开发人员来说是一个非常有用的应用语言。不过其中还有许多比较高深的内容值得我们去花大量的时间去学习。在这里就先为大家介绍一下有关C++使用接口的实现

C++编程语言的应用对于开发人员来说是一个非常有用的应用语言。不过其中还有许多比较高深的内容值得我们去花大量的时间去学习。在这里就先为大家介绍一下有关C++使用接口的实现方法。

面向对象的语言诸如JAVA提供了Interface来实现接口,但C++却没有这样一个东西,尽管C++ 通过纯虚基类实现接口,譬如COM的C++实现就是通过纯虚基类实现的(当然MFC的COM实现用了嵌套类),但我们更愿意看到一个诸如 Interface的东西。下面就介绍一种解决办法。

首先我们需要一些宏:

  1. //  
  2. // Interfaces.h  
  3. //  
  4. #define Interface class  
  5. #define DeclareInterface(name) Interface name {   
  6. public:   
  7. virtual ~name() {}  
  8. #define DeclareBasedInterface(name, base) class name :  
  9. public base {   
  10. public:   
  11. virtual ~name() {}  
  12. #define EndInterface };  
  13. #define implements public 

有了这些宏,我们就可以这样定义我们的接口了:

  1. //  
  2. // IBar.h  
  3. //  
  4. DeclareInterface(IBar)  
  5. virtual int GetBarData() const = 0;  
  6. virtual void SetBarData(int nData) = 0;  
  7. EndInterface 

是不是很像MFC消息映射那些宏啊,熟悉MFC的朋友一定不陌生。现在我们可以像下面这样来实现C++使用接口这一功能:

  1. //  
  2. // Foo.h  
  3. //  
  4. #include "BasicFoo.h"  
  5. #include "IBar.h"  
  6. class Foo : public BasicFoo, implements IBar  
  7. {  
  8. // Construction & Destruction  
  9. public:  
  10. Foo(int x) : BasicFoo(x)  
  11. {  
  12. }  
  13. ~Foo();  
  14. // IBar implementation  
  15. public:  
  16. virtual int GetBarData() const  
  17. {  
  18. // add your code here  
  19. }  
  20. virtual void SetBarData(int nData)  
  21. {  
  22. // add your code here  
  23. }  
  24. }; 

怎么样,很简单吧,并不需要做很多的努力我们就可以实现C++使用接口这一操作了。

精彩图集

赞助商链接