c下基于对象编程
c语言下实现基于对象的编程方法,这里的用基于对象编程,并不是面向对象编程。因为其简单实现基于对象编程,并不能完全实现面向对象编程。
第一种方式实现部分面向对象:就是在子结构体中引用另外一个结构体指针,从而实现部分继承。
第二种方式:父结构体中存在一个私有引用指针,而实现这个私有指针的操作是由对象意义上的子类去完成实现。下面是一个例子。
person.c如下:
#include <stdio .h> #include <stdlib .h> #include <string .h> #include "person.h" void* newPerson(const char *name,int age) { Person *person = malloc(sizeof(Person)); person->name = strdup(name); person->age = age; person->priSalary = NULL; return (person); } void deletePerson(void * ptr) { Person * person = (Person*)ptr; free(person->name); free(person); } void displayPerson(void *ptr) { Person *person = (Person*)ptr; printf("< <<Output the person information>>>>\n"); printf("the name %s, the age = %d\n",person->name,person->age); printf("< <<End the person>>>\n"); }
student.c如下:
#include <stdio .h> #include <stdlib .h> #include <string .h> #include "student.h" #include "person.h" void * newStudent(const char * name) { Person * student = malloc(sizeof(Person)); student->name = strdup(name); student->age = 10; student->priSalary = malloc(sizeof(Student)); ((Student * )student->priSalary)->score = 5; return (student); } void displayStudent(void* student) { displayPerson(student); printf("the score = %d\n",((Student *)((Person *)student)->priSalary)->score); } void deleteStudent(void * student) { printf("delete the student\n"); free(((Person *)student)->name); free(((Person *)student)->priSalary); }