面向对象C编程--继承

在 C 语言中,面向对象的继承属性可以使用结构体嵌套和函数指针实现。下面是一个示例程序:

#include <stdio.h>

// 定义父类结构体
typedef struct {
    int age;
    char *name;
} Parent;

// 定义父类的方法
void (*parent_say_hello)(Parent *);

void parent_init(Parent *self, int age, char *name) {
    self->age = age;
    self->name = name;
}

void parent_say_hello_impl(Parent *self) {
    printf("Hello, my name is %s and I am %d years old.\n", self->name, self->age);
}

// 定义子类结构体,并在其中嵌套父类结构体
typedef struct {
    Parent parent;
} Child;

// 定义子类的方法
void (*child_say_hello)(Child *);

void child_init(Child *self, int age, char *name) {
    // 调用父类的初始化方法
    parent_init(&self->parent, age, name);
}

void child_say_hello_impl(Child *self) {
    // 调用父类的方法
    parent_say_hello(&(self->parent));
    printf("I am a child.\n");
}

int main() {
    Parent p;
    parent_say_hello = &parent_say_hello_impl;
    parent_init(&p, 30, "John");
    parent_say_hello(&p);

    Child c;
    child_say_hello = &child_say_hello_impl;
    child_init(&c, 5, "Tom");
    child_say_hello(&c);

    return 0;
}

在这个程序中,我们首先定义了一个父类 Parent,其中包含了年龄和名字两个属性。为了实现多态,我们将父类的方法 say_hello 定义成函数指针 parent_say_hello。然后我们实现了父类的初始化方法 parent_init 和 say_hello 方法的具体实现 parent_say_hello_impl。

接着,我们定义了子类 Child,并在其中嵌套了父类 Parent。为了重写父类的方法,我们在子类中重新定义了一个 say_hello 方法,并将其定义为函数指针 child_say_hello。在子类的初始化方法 child_init 中,我们调用了父类的初始化方法来初始化父类的属性。在子类的 say_hello 方法的具体实现 child_say_hello_impl 中,我们先调用了父类的 say_hello 方法,然后输出了一个额外的字符串,以表明这是子类的 say_hello 方法。

最后,在 main 函数中,我们分别创建了父类和子类的对象,并调用它们的 say_hello 方法,以验证继承和多态的正确性。

【最后一个bug】多平台都有更新和发布,大家可以一键三连,关注+星标,不错过精彩内容~
在这里插入图片描述

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值