当前位置:   article > 正文

类的C语言模拟实现_c实现类

c实现类

类的C语言实现

摘自:《嵌入式C语言自我修养:从芯片、编译器到操作系统》

C++语言可以使用class关键字定义一个类,C语言中没有class关键字,但是我们可以使用结构体来模拟一个类,C++类中的属性类似结构体的各个成员。虽然结构体内部不能像类一样可以直接定义函数,但我们可以通过在结构体中内嵌函数指针来模拟类中的方法。如上面C++代码中定义的Animal类,我们也可以使用一个结构体来表示。

struct animal{
    int age;
    int weight;
    void (*fp)(void);
}
  • 1
  • 2
  • 3
  • 4
  • 5

如果一个结构体中需要内嵌多个函数指针,则我们可以把这些函数指针进一步封装到一个结构体内。

struct func_operations{
	void (*fp1)(void);
	void (*fp2)(void);
	void (*fp3)(void);
	void (*fp4)(void);
}
struct animal{
	int age;
	int weight;
	struct func_operations fp;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

通过以上封装,我们就可以把一个类的属性和方法都封装在一个结构体里了。封装后的结构体此时就相当于一个“类”,子类如果想使用该类的属性和方法,该如何继承呢?

struct cat{
	struct animal *p;
	struct animal ani;
	char sex;
	void (*eat)(void);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

C语言可以通过在结构体中内嵌另一个结构体或结构体指针来模拟类的继承。如上所示,我们在结构体类型cat里内嵌结构体类型animal,此时结构体cat就相当于模拟了一个子类cat,而结构体animal相当于一个父类。通过这种内嵌方式,子类就“继承”了父类的属性和方法。我们写一个测试程序,代码如下

//cat.c
#include <stdio.h>
void speak(void){
	printf("animal speaking...\n");
}
struct func_operations{
	void (*fp1)(void);
	void (*fp2)(void);
	void (*fp3)(void);
	void (*fp4)(void);
};
struct animal{
	int age;
	int weight;
	struct func_operations fp;
};
struct cat{
	struct animal *p;
	struct animal ani;
	char sex;
};
int main(void){
	struct animal ani;
	ani.age = 1;
	ani.weight = 2;
	ani.fp.fp1 = speak;
	printf("%d,%d\n",ani.age,ani.weight);
	ani.fp->fp1();

	struct cat c;
	c.p = &ani;
	c.p->fp->fp1();
	printf("%d,%d\n",c.p->age,c.p->weight);

	return 0;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36

程序运行结果如下

1 2
animal speaking...
animal speaking...
1 2
  • 1
  • 2
  • 3
  • 4

我们使用结构类型定义一个变量,模拟使用类来实例化一个对象。为了实现继承,我们需要宽松面向对象编程中的关于“继承”的定义:在C语言中,内嵌结构体或内嵌指向结构体的指针,都可以看作对“继承”的模拟。在上面的测试代码中,结构体类型cat中的指针变量p指向了animal结构体,然后就可以通过p去使用结构体类型animal中的属性和方法来模拟类的继承

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/43732
推荐阅读
相关标签
  

闽ICP备14008679号