#include<string>
#include<iostream>
using namespace std;
struct Shape;
typedef const string& (*GetName)(Shape* shape);
typedef void (*Draw)(Shape* shape);
typedef struct VTable{//虚表的定义
GetName getName;
Draw draw;
}VTable;
const string& getNameTriangle(Shape* shape);
const string& getNameCircle(Shape* shape);
void drawTriangle(Shape* shape);
void drawCircle(Shape* shape);
static VTable vtableTriangle={getNameTriangle,drawTriangle};//初始化虚表
static VTable vtableCircle={getNameCircle,drawCircle};
typedef struct Shape{//定义基类形状
string name;
VTable* vptr;
}Shape;
//下面两个宏定义用来得到实际的指针
#define OFFSET(TYPE,MEMBER) ((unsigned int)&(((TYPE*)NULL)->MEMBER))
#define GET_CONTAINER_PTR(TYPE,MEMBER,MEMBERPTR) ((TYPE*)((unsigned int)MEMBERPTR-OFFSET(TYPE,MEMBER)))
typedef struct Triangle{//定义三角形,相当于从Shape public继承而来
Shape base;
int a,b,c;
}Triangle;
void initTriangle(Triangle* tr
用c语言实现面向对象的封装继承和多态
最新推荐文章于 2022-03-03 18:35:39 发布
这篇博客通过C语言展示了如何实现面向对象编程的基本概念,包括封装、继承和多态。通过定义虚表(VTable)和宏定义,实现了基类Shape以及派生类Triangle和Circle。每个类都有相应的getName和draw方法,通过虚表调用这些方法实现了多态性。在main函数中,创建了Triangle和Circle对象,并使用统一的drawShape和getShapeName函数进行操作,体现了面向对象的特性。
摘要由CSDN通过智能技术生成