qq空间怎么做网站,wordpress文章批量发布,北京城乡建设和住房门户网站,麻城建设局网站停办文章目录 封装继承多态 封装
封装是把一个抽象的事物的属性以及对应的操作打包到一个类中#xff0c;通过内部的方法来改变内部的状态#xff0c;封装的本质是在隐藏信息#xff0c;使得对象内部的状态不轻易被外界访问和利用。
但是c语言没有类的概念#xff0c;c语言实… 文章目录 封装继承多态 封装
封装是把一个抽象的事物的属性以及对应的操作打包到一个类中通过内部的方法来改变内部的状态封装的本质是在隐藏信息使得对象内部的状态不轻易被外界访问和利用。
但是c语言没有类的概念c语言实现封装可以使用结构体来实现。
#includestdio.h
#includestring.h
#includestdlib.h
typedef struct human{int age;char sex[10];void (*set_age)(struct human *p,int age);int (*get_age)(struct human *p);void (*set_sex)(struct human *p,char* sex);char* (*get_sex)(struct human *p);
}human;void set_age(human *p,int age){p-ageage;
}
int get_age(human *p){return p-age;
}void set_sex(human *p,char* sex){strcpy(p-sex,sex);//p-sexsex;
}
char* get_sex(human *p){return p-sex;
}int main(){human p{18,female,set_age,get_age,set_sex,get_sex};printf(年龄%d\n,p.get_age(p));printf(性别%s\n,p.get_sex(p));p.set_age(p,19);p.set_sex(p,male);printf(年龄%d\n,p.get_age(p));printf(性别%s\n,p.get_sex(p));}定义一个human的结构体结构体具有两个属性为age和sex有两组方法分别为设置输入与获取的方法。 继承
继承是基于一个已有的类父类再创建一个新的类子类新的类可以访问父类的属性和动作从而避免重复编写代码。需要注意的是父类需要放在子类的数据结构的第一个数据成员。子类可以有自己的属性。
在c语言中可以使用结构体嵌套的方法实现类的继承单继承。
#includestdio.h
#includestring.h
#includestdlib.h
typedef struct human{int age;char sex[10];void (*set_age)(struct human *p,int age);int (*get_age)(struct human *p);void (*set_sex)(struct human *p,char* sex);char* (*get_sex)(struct human *p);
}human;typedef struct person{human p;char name[10];
}person;void set_age(human *p,int age){p-ageage;
}
int get_age(human *p){return p-age;
}void set_sex(human *p,char* sex){strcpy(p-sex,sex);//p-sexsex;
}
char* get_sex(human *p){return p-sex;
}person * create_person(int age,char* sex, char* name){person* per(person*)malloc(sizeof(person));per-p.ageage;strcpy(per-p.sex,sex);strcpy(per-name,name);return per;
}int main(){person* per;percreate_person(18,male,Job);printf(年龄%d\n性别%s\n姓名%s\n,per-p.age,per-p.sex,per-name);}person继承了human中的两个属性使用结构体的嵌套可以实现c语言的继承。 多态
多态是面向对象编程中最为核心的概念它允许我们在不同的对象上执行相同的操作。
在c语言中可以使用函数指针利用同一个接口来处理不同的数据。具有不同的功能的函数可以使用同一个函数名从而实现一个函数名调用不同的功能函数。
#includestdlib.h
#includestdio.h
#includestring.htypedef struct{void (*draw)(void* shape);
}Shape;typedef struct{Shape base;int x;int y;int r;
}Circle;typedef struct{Shape base;int x1;int y1;int x2;int y2;
}Line;void drawCircle(void* shape){Circle* circle(Circle*)shape;printf(Circle at(%d,%d)with radius %d\n,circle-x,circle-y,circle-r);
}void drawLine(void *shape){Line* line(Line *)shape;printf(Line from(%d,%d)to(%d,%d)\n,line-x1,line-y1,line-x2,line-y2);
}int main(){int i0;Circle circle{{drawCircle},0,0,1};Line line{{drawLine},0,0,1,1};Shape* shapes[2];shapes[0](Shape*)circle;shapes[1](Shape*)line;for(;i2;i) shapes[i]-draw(shapes[i]);return 0;
}