C + + interface definition and implementation examples
I. Definition of interface
Sometimes, we have to provide some interface for others to use. The function of an interface is to provide a way to interact with other systems. Other systems do not need to understand your internal details, and can not understand internal details, only through the interface you provide to the external to communicate with you. According to the characteristics of C + +, we can use pure virtual function of the way to achieve. The advantage of this is the ability to implement encapsulation and polymorphism. An example is given for your reference. (Do not want to do too much explanation, you should be able to understand a look)
Class IPerson
{
Public
IPerson () {};
Virtual ~iperson () =0 {}; Note that it is best to define this virtual destructor to prevent subclasses from calling destructors correctly, and if you are defined as a pure virtual destructor, you must take the definition body, because the subclass implicitly invokes the destructor.
The interfaces provided to the outside use are generally pure virtual functions
virtual void SetName (const string &strname) = 0;
Virtual const string GetName () = 0;
virtual void Work () = 0;
}
Second, interface implementation
Implementation interfaces are implemented by inheriting subclasses of interfaces, and different subclasses can achieve different effects, even when called polymorphic.
Class Cteacher:public IPerson
{
Public
Cteacher () {};
Virtual ~cteacher ();
String M_strname;
void SetName (const string &strname);
Const string GetName ();
void Work ();
}
void Cteacher::setname (const string &strname)
{
M_strname = name;
}
Const string Cteacher::getname ()
{
return m_strname;
}
void Cteacher::work ()
{
cout << "I am teaching!" <<endl;//the job of a teacher is to teach, and the work of other professions is different.
}
Third, interface export
BOOL Getipersonobject (void** _rtobject)
{
iperson* Pman = NULL;
Pman = new Cteacher ();
*_rtobject = (void*) Pman;
return true;
}
__declspec (dllexport) bool Getipersonobject (void** _rtobject);
Four, interface use
#include "IPerson.h"
#pragma comment (lib, "IPerson.lib")
BOOL __declspec (dllimport) getipersonobject (void** _rtobject);
/* Test Example * *
void Main ()
{
IPerson * _ipersonobj = NULL;
void* Pobj=null;
if (Getipersonobject (&pobj))
{
Get Object
_ipersonobj = (IPerson *) pobj;
Calling an interface, performing an action
_ipersonobj->setname ("Tom");
String strName = _ipersonobj->getname;
_ipersonobj->work ();
}
if (_ipersonobj!=null)
{
Delete _ipersonobj;
_ipersonobj = NULL;
}
}
So far, the basic complete demonstration of the definition and implementation of the interface, there are deficiencies, please advise. ^-^...