C语言是利用结构体来实现类的效果的。当然,跟类还是有不同,在C++中类的成员属性默认是私有(private)的,而结构体是公开的(public)。
那么应该如何实现类的继承效果呢?我们可以利用结构体嵌套来实现,将”父类“当作”子类“的一部分,那可不就是继承了吗?
#include<stdio.h>
typedef struct A{
int a;
}A;
typedef struct B{
struct A B_A;
}B;
int main(){
B b;
b.B_A.a = 10;
printf("%d\n",b.B_A.a);
}
//输出结果为10
现在写一个继承[C语言]实现类效果中ppi类的例子,此处对ppi类中形参“struct ppi this”修改成了“struct ppi *this”,以解决参数类型不匹配问题。
connect.h
#ifdef __cplusplus //****** ADD
extern "C" { //****** ADD
#endif //****** ADD
#define LINUX
#ifdef LINUX
typedef struct connect{
int protocol_read;
int protocol_write;
struct ppi *PPI;
void (*Read)(struct connect this,int area,int para1,int para2,int para3);
void (*Write)(struct connect this,int area,int para1,int para2,int para3,int *value);
}connect;
connect *NewConnect(connect *this);
void Read(struct connect this,int area,int para1,int para2,int para3);
void Write(struct connect this,int area,int para1,int para2,int para3,int *value);
#endif
#ifdef __cplusplus
}
#endif
connect.c
#include<stdlib.h>
#include<stdio.h>
#include<stdbool.h>
#include"nodavesimple.h"
#include"setport.h"
#include"ppi.h"
#include"protocol.h"
connect *NewConnect(connect *this){
this->protocol_read = 0;
this->protocol_write = 0;
}
void Read(struct connect this,int area,int para1,int para2,int para3){
switch(this.protocol_read){
case 0:
printf("para 'protocol_read' ERROR!\n");
break;
case 1:
this.PPI = (struct ppi*)malloc(sizeof(struct ppi));
NewPPI(this.PPI);
ReadBytes(this.PPI,area,para1,para2,para3,NULL);
free(this.PPI);
break;
default:
printf("this protocol is not support!\n");
break;
}
}
void Write(struct connect this,int area,int para1,int para2,int para3,int *value){
switch(this.protocol_write){
case 0:
printf("para 'protocol_read' ERROR!\n");
break;
case 1:
this.PPI = (struct ppi*)malloc(sizeof(struct ppi));
NewPPI(this.PPI);
WriteBytes(this.PPI,area,para1,para2,para3,value);
free(this.PPI);
break;
default:
printf("this protocol is not support!\n");
break;
}
}
/*
int main(){
ppi PPI;
NewPPI(&PPI);
int a = 0x2F;
// PPI.WriteBytes(PPI,daveOutputs,0,0,1,&a);
PPI.ReadBytes(PPI,daveOutputs,0,0,2,NULL);
return 0;
}//use to test ppi class && need delete protocol.h
*/