C语言模拟面向对象实例

C语言本身不支持面向对象,但通过结构体和函数指针等方式可以模拟实现面向对象的思想。在下面的示例中,我们将演示如何使用C语言实现封装、抽象、继承和多态。

 
#include <stdio.h>
#include <stdlib.h>

//定义一个人类 Person
typedef struct {
    char* name;
    int age;
} Person;

//定义一个学校类 School
typedef struct {
    char* name;
    char* address;
    void (*introduce)(Person*);
} School;

//定义一个学生类 Student,它继承了 Person 类
typedef struct {
    Person person; // 继承自 Person 类
    School* school;
    void (*study)(void);
} Student;

// 封装:创建并初始化一个 Person 对象
Person* create_person(char* name, int age) {
    Person* person = (Person*) malloc(sizeof(Person));
    person->name = name;
    person->age = age;
    return person;
}

// 抽象:为 Person 类增加一个介绍自己的方法 introduce
void introduce_person(Person* person) {
    printf("My name is %s and I am %d years old.\n", person->name, person->age);
}

// 抽象:为 School 类增加一个介绍自己的方法 introduce
void introduce_school(School* school) {
    printf("I am a school called %s located at %s.\n", school->name, school->address);
}

// 多态:为学生类 Student 增加一个 study 方法,使其能够学习不同的科目
void study_math(void) {
    printf("I am studying math.\n");
}

void study_english(void) {
    printf("I am studying English.\n");
}

// 继承:创建并初始化一个 Student 对象
Student* create_student(char* name, int age, char* school_name, char* school_address) {
    // 创建 Person 对象
    Person* person = create_person(name, age);

    // 创建 School 对象
    School* school = (School*) malloc(sizeof(School));
    school->name = school_name;
    school->address = school_address;
    school->introduce = introduce_school;

    // 创建 Student 对象
    Student* student = (Student*) malloc(sizeof(Student));
    student->person = *person;
    student->school = school;
    student->study = study_math; // 默认学习数学

    return student;
}

int main() {
    // 创建一个名为 Tom,年龄为 18 岁的学生对象
    Student* tom = create_student("Tom", 18, "ABC School", "123 Road");

    // 调用学校类的介绍方法
    tom->school->introduce(tom->person);

    // 调用学生类的介绍方法
    introduce_person(&tom->person);

    // 调用学生对象的 study 方法
    tom->study();

    // 更改学生对象的学习方法为英语
    tom->study = study_english;

    // 再次调用学生对象的 study 方法
    tom->study();

    // 释放内存
    free(tom->school);
    free(tom);

    return 0;
}

在上述代码中,我们定义了三个类:Person、School 和 Student。其中 Person 为基类,School 为派生类并包含一个介绍自己的方法 introduce,Student 也是派生类,继承了 Person 类,并且添加了学校和学习方法等属性。

在 create_person 和 create_student 函数中,我们使用 malloc 分配内存,并返回相应的对象指针。在 introduce_person 和 introduce_school 函数中,我们定义了介绍自己的方法。在 study_math 和 study_english 函数中,我们定义了两个不同的学习方法。

最后,在 main 函数中,我们创建了一个名为 Tom,年龄为 18 岁的学生对象,并调用了其各个属性的方法。同时,我们还演示了多态特性,通过更改学生对象的学习方法,使其能够学习不同的科目

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值