【C語言】實作類的繼承
C語言如何實作類的效果?
結構體跟類是一種比較類似的結構,都對成員進行了一定程度的封裝。差別在于,結構體的成員預設是public,類的成員預設是private。
.h檔案
#ifdef __cplusplus //****** ADD
extern "C" { //****** ADD
#endif //****** ADD
#ifdef BCCWIN
#ifdef DOEXPORT
#define EXPORTSPEC __declspec (dllexport)
#else
#define EXPORTSPEC __declspec (dllimport)
#endif
EXPORTSPEC HANDLE __stdcall setPort(char * name, char* baud,char parity);
EXPORTSPEC int __stdcall closePort(HANDLE port);
#endif
//#ifdef __cplusplus //****** REMOVE moved to top
//extern "C" { //****** REMOVE moved to top
//#endif //****** REMOVE moved to top
#define LINUX
#ifdef LINUX
typedef struct ppi{
long a,b,c,e;
int int_a;
int res;
float d;
bool isSucceed;
daveInterface * di;
daveConnection * dc;
_daveOSserialType fds;
void (*ReadBytes)(struct ppi this,int area,int para1,int para2 ,int para3,int *CopyToBuffer);
void (*WriteBytes)(struct ppi this,int area,int para1,int para2,int para3,int *theAreaOfValue);
}ppi;
void ReadBytes(struct ppi this,int area ,int para1,int para2,int para3,int *CopyToBuffer);
void WriteBytes(struct ppi this,int area ,int para1,int para2,int para3,int *theAreaOfValue);
ppi *NewPPI(ppi *this);
#endif
#ifdef __cplusplus
}
#endif
.c檔案
#include#include#include#include"nodavesimple.h"
#include"setport.h"
#include"ppi.h"
void ReadBytes(struct ppi this,int area ,int para1,int para2,int para3,int *CopyToBuffer){
if(this.isSucceed){
//printf("",);
this.res = daveReadBytes(this.dc,area,para1,para2,para3,CopyToBuffer);
printf("res=%d\n",this.res);
this.int_a = daveGetU16(this.dc);
printf("U16:0x%X\n",this.int_a);
}else{
printf("error!could not open serial port /dev/ttyUSB0 \n");
}
}
void WriteBytes(struct ppi this,int area ,int para1,int para2,int para3,int *theAreaOfValue){
if(this.isSucceed){
printf("Write\n");
this.res = daveWriteBytes(this.dc,area,para1,para2,para3,theAreaOfValue);
}else{
printf("error!could not open serial port /dev/ttyUSB0 \n");
}
}
ppi *NewPPI(ppi *this){
//(this->fds).rfd = serPort("/dev/ttyUSB0","9600",'E');
//(this->fds).wfd = (this->fds).rfd;
if((this->fds).rfd>0){
this->isSucceed = true;
this->di =daveNewInterface(this->fds, "IF1", 0, daveProtoPPI, daveSpeed187k);
this->dc =daveNewConnection(this->di, 2, 0, 0);
daveConnectPLC(this->dc);
}else{
this->isSucceed = false;
}
this->ReadBytes = ReadBytes;
this->WriteBytes = WriteBytes;
}
【C語言】實作類的繼承