需求

cpp 实现类似 java 的 interface

解决

interface 关键字

因为 interface 所有声明默认都是 public=,所以选择 =struct.

#define interface struct;
#define implements public

使用

#include "Interface.h"

Interface IBar
{
public:
    virtual ~IBar(){}
    virtual int getBarData() const = 0;
    virtual void setBarData(int nData) = 0;
};
class Bar :public BasicBar,implements IBar
{
public:
    Bar(int x=0) : BasicBar(x)
    {
    }
    ~Bar(){}
    virtual int getBarData() const
    {
      std::cout <<"Get Bar!";
      return 0;
    }
    virtual void setBarData(int nData)
    {
    }
};

class DataAccess
{
    // Construction & Destruction
public:
    DataAccess()
    {
    }
    ~DataAccess()
    {
    }
    static IBar* createBar()
    {
      //返回对象给IBar接口
      return(new Bar());
    }

};
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    //IBar *bar = new Bar();
    IBar *bar = DataAccess::createBar();
    bar->getBarData();
    delete bar;
    return a.exec();
}

注意点

实现接口的虚析构函数一定要有,不然容易出问题,比如下面这样,就有可能内存泄漏.

int main()
{
   IBar* pBar = BarFactory::CreateBar(Bar);
   pBar->SetName("MyFooBar");
   delete pBar;    // Oops!
}

参考

C++接口实现总结

C++接口实现总结(Interface)

C++的interface

c++ 如何编写接口类(interface)

C++中实现类似java中接口的功能