接口是一个没有被实现的特殊的类,它是一系列操作的集合,我们可以把它看作是与其他对象通讯的协议。C++中没有提供类似interface这样的关键 字来定义接口,但是Mircrosoft c++中提供了__declspec(novtable)来修饰一个类,来表示该类没有虚函数表,也就是虚函数都是纯虚的。所以利用它我们依然可以定义一 个接口。代码例子如下:
#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;
}
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接口等价于下面的定义:
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; };