C ++ programming language is a very useful application language for developers. However, there are still a lot of advanced content that we should spend a lot of time learning. Here we will first introduce the implementation of the c ++ interface.
Object-oriented languages such as JAVA provide interfaces to implement interfaces, but C ++ does not. Although C ++ implements interfaces through pure virtual base classes, for example, the C ++ Implementation of COM is implemented through the pure virtual base class. Of course, the COM Implementation of MFC uses Nested classes), but we prefer to see something like Interface. The following describes a solution.
First, we need some macros:
- //
- // 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
With these macros, we can define our interfaces as follows:
- //
- // IBar.h
- //
- DeclareInterface(IBar)
- virtual int GetBarData() const = 0;
- virtual void SetBarData(int nData) = 0;
- EndInterface
Isn't it like the macros for message ing in MFC? friends who are familiar with MFC must be familiar with it. Now we can implement the function of using the C ++ interface as follows:
- //
- // 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
- }
- };
It's easy. We don't need to make a lot of effort to implement the C ++ interface operation.