2011年6月14日 星期二

Using Interfaces in C++

Method 1.
#include "objbase.h"  //~~~!! for interface identifier
#include "stdio.h"


interface IAnimal
{
    virtual void Forward() = 0;
    virtual void Eat() = 0;
};

class CBird : public IAnimal
{
 
virtual  void Forward()
    {
        printf( "walk 3 steps \n" );
    };
  
virtual void Eat()
    {
        printf( "eat 5 rice \n" );
    };
};


void main()
{  
    IAnimal *pAnm = NULL;
    CBird bird;
  
    pAnm = &bird;
    pAnm->Forward();
  }

In this method, you need to #include "objbase.h". And write pure virtual func. in the interface class.

Method 2.
In VS7 Microsoft has judged __interface introduction in c++ compiler( macOS c++  support?...)  In the msdn  __interface definition:
  • Can inherit from zero or more base interfaces.
  • Cannot inherit from a base class.
  • Can only contain public, pure virtual methods.
  • Cannot contain constructors, destructors, or operators.
  • Cannot contain static methods.
  • Cannot contain data members; properties are allowed.
Therefore, we can adjust our sample code:
//#include "objbase.h"    // doesn't be required
__interface IAnimal
{
    void Forward();         //also can be virtual
void Forward() = 0; , but redundant
    void Eat();                //also can be virtual void Eat() = 0; , but redundant
};

Method 3.
We can apply the Method 2., and integrate with Macro code.

#define Interface class
#define implements public

#define DeclareInterface(name) __interface name {

#define DeclareBasedInterface(name, base) __interface name \
    : public base {

#define EndInterface(name)                 \
     };


DeclareInterface(IAnimal)
    void Forward();
    void Eat();
EndInterface(IAnimal)


Reference:
http://www.codeguru.com/cpp/cpp/cpp_mfc/oop/article.php/c9989
http://blog.yam.com/swwuyam/article/13090970

沒有留言:

張貼留言