接口是一個(gè)沒有被實(shí)現(xiàn)的特殊的類,它是一系列操作的集合,我們可以把它看作是與其他對(duì)象通訊的協(xié)議。C++中沒有提供類似interface這樣的關(guān)鍵 字來(lái)定義接口,但是Mircrosoft c++中提供了__declspec(novtable)來(lái)修飾一個(gè)類,來(lái)表示該類沒有虛函數(shù)表,也就是虛函數(shù)都是純虛的。所以利用它我們依然可以定義一 個(gè)接口。代碼例子如下:
#include <IOSTREAM>
using namespace std;
#define interface class __declspec(novtable)
interface ICodec
{
public:
virtual bool Decode(char * lpDataSrc,unsigned int nSrcLen,char * lpDataDst,unsigned int *pnDstLen);
virtual bool Encode(char * lpDataSrc,unsigned int nSrcLen,char * lpDataDst,unsigned int *pnDstLen);
};
class CCodec : public ICodec
{
public:
virtual bool Decode(char * lpDataSrc,unsigned int nSrcLen,char * lpDataDst,unsigned int *pnDstLen)
{
cout << "解碼..." << endl;
return true;
}
virtual bool Encode(char * lpDataSrc,unsigned int nSrcLen,char * lpDataDst,unsigned int *pnDstLen)
{
cout << "編碼..." << endl;
return true;
}
};
int main(int argc, char* argv[])
{
ICodec * pCodec = new CCodec();
pCodec->Decode(NULL,0,NULL,NULL);
pCodec->Encode(NULL,0,NULL,NULL);
delete (CCodec*)pCodec;
return 0;
}
上面的ICodec接口等價(jià)于下面的定義:
class ICodec
{
public:
virtual bool Decode(char * lpDataSrc,unsigned int nSrcLen,char * lpDataDst,unsigned int *pnDstLen)=0;
virtual bool Encode(char * lpDataSrc,unsigned int nSrcLen,char * lpDataDst,unsigned int *pnDstLen)=0;
};