(1)struct实现class
struct内部变量等效于class成员变量;
struct内部函数指针等效于class成员函数;
typedef struct point_t
{
int x;
int y;
void (*setPoint)(struct point_t *pP,int x, int y);//传递point_t指针参数,以确定被操作对象
} point_t;
void setPoint(struct point_t *pP,int x, int y)
{
pP->x = x;
pP->y = y;
}
void main()
{
struct point_t m_p=
{//可乱序初始化风格
.x=0,
.y=0,
.setPoint=setPoint//初始化函数指针
};
m_p.setPoint(&m_p,10,10);
printf("x=%d,y=%d\n",m_p.x,m_p.y);
}
(2)将struct A作为struct B第一个元素,可实现“继承”以及“父子”间的强制转换
typedef struct point_display_t
{
point_t p;//“继承”
void (*displayPoint)(struct point_display_t *pDis);//传递point_display_t 指针参数,以确定被操作对象
} point_display_t;
{
printf("x=%d,y=%d\n",pDis->p.x,pDis->p.y);
}
//接(1)
void main()
{
struct point_t m_p=
{
.x=0,
.y=0,
.setPoint=setPoint//初始化函数指针
};
struct point_display_t m_dis=
{
.p=m_p,//复制
.displayPoint=displayPoint
};
m_p.setPoint(&m_p,10,10);
m_dis.displayPoint(&m_dis);//输出x=0,y=0
struct point_t *p_point;
struct point_display_t *p_point_display;
m_dis.p.setPoint(&(m_dis.p),20,20);
m_dis.displayPoint(&m_dis);//输出x=20,y=20
p_point=(point_t *)&m_dis;//子类型转为父类型
printf("x=%d,y=%d\n",p_point->x,p_point->y);//输出x=20,y=20
p_point_display = (point_display_t *)p_point;
p_point_display->displayPoint(p_point_display);//输出x=20,y=20
}
ps:指针强制转换其实就是内存地址的直接赋值,然后根据强制转换后的类型特有的形式访问内存。只要访问内存的方法正确,则能访问成功。