C语言面向对象

C语言通过函数指针实现[封装,继承,多态]

#include 
#include 
#include 
#include 

//封装
typedef struct Teacher{
    char * name;
    //函数指针(传递参数是为了让该函数只能被Teacher调用)
    void (*print)(struct Teacher * pT);
}Teacher;
void Teach_Print(Teacher * pT){
    printf("name = [%s]\n",pT->name);
}

//继承
typedef struct Student{
    Teacher teacher;
    //函数指针
    int (*getLength)(struct Student * stu);
}Student;

int Stu_getLength(Student * stu){
    return strlen(stu->teacher.name);
}

//继承2
typedef struct Bigstudent{
    Teacher * teacher;
    //函数指针
    int (*getLength)(struct Bigstudent * bstu);
}Bigstudent;
int bstu_getLength(Bigstudent * bstu){
    return strlen(bstu->teacher->name);
}

//多态
typedef struct Person{
    void (*person)(struct Person * ps);
}Person;
void getPsInfo(Person * ps){
    printf(" PS::person \n");
}

typedef struct ManPerson{
    Person * ps;
    void (*manps)(struct ManPerson * mps);
}ManPerson;
void getManPsInfo(ManPerson * mps){
    printf("MPS::Man person\n");
}

typedef struct WomanPerson{
    Person * ps;
    void (*wmps)(struct WomanPerson * wps);
}WomanPerson;
void getWoManPsInfo(WomanPerson * wps){
    printf("WPS::Women person\n");
}

//=================================================

int main()
{


    /* //封装 Teacher * t = NULL; t = (Teacher *)malloc(sizeof(Teacher)); t->name = "lcmm"; t->print = Teach_Print; t->print(t); free(t); */

    /* //继承 int length = 0; Student * stu = NULL; stu = (Student *)malloc(sizeof(Student)); stu->teacher.name = "lcmm"; stu->teacher.print = Teach_Print; stu->getLength = Stu_getLength; stu->teacher.print(&(stu->teacher)); length = stu->getLength(stu); printf("length = %d\n",length); free(stu); //继承2 int newlength = 0; Bigstudent * bstu = (Bigstudent *)malloc(sizeof(Bigstudent)); bstu->teacher = (Teacher *)malloc(sizeof(Teacher)); bstu->teacher->name = "ubuntu linux"; bstu->teacher->print = Teach_Print; bstu->getLength = bstu_getLength; bstu->teacher->print(bstu->teacher); newlength = bstu->getLength(bstu); printf("length = %d\n",newlength); free(bstu->teacher); free(bstu); */

    /* //多态 ManPerson * mps = NULL; mps = (ManPerson *)malloc(sizeof(ManPerson)); mps->ps = (Person *)malloc(sizeof(Person)); mps->ps->person = getPsInfo; mps->ps->person(mps->ps); mps->manps = getManPsInfo; mps->manps(mps); //====================== WomanPerson * wps = NULL; wps = (WomanPerson *)malloc(sizeof(WomanPerson)); wps->ps = (Person *)malloc(sizeof(Person)); wps->ps->person = getPsInfo; wps->ps->person(wps->ps); wps->wmps = getWoManPsInfo; wps->wmps(wps); free(mps->ps); free(mps); free(wps->ps); free(wps); */

    return 0;
}

你可能感兴趣的:(C语言基础)