在 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】多平台都有更新和发布,大家可以一键三连,关注+星标,不错过精彩内容~