C语言面向对象的封装、继承和多态的思想

#include <stdio.h>
#include <stdlib.h>
#define Jicheng
#define Fengzhuang
#define Duotai
/*思想为结构体的嵌套*/
#ifdef Jicheng   
struct jichengfirst {
 int num;
};

struct jichengsecond {
 double tw;
};

struct jichengthird {   //继承jichengfirst和jichengsecond两个结构体
 int mine;
 struct jichengfirst first;
 struct jichengsecond second;
};
#endif

/*思想为结构体的嵌套*/
#ifdef Fengzhuang    
struct fengzhuangbase {   //需要封装的结构体
 int base;
};

struct fengzhuang {    //封装
 struct fengzhuangbase *base;
};

int constructor(struct fengzhuang *f) //建立封装了的结构体
{
 f->base = (fengzhuangbase *)malloc(sizeof(fengzhuangbase));
 if (!f->base)
  return -1;
 return 0;
}

int get(struct fengzhuang *f) //获得封装结构体中数据
{
 return f->base->base;
}

void set(struct fengzhuang *f,int data)  //数据写入封装结构体
{
 f->base->base = data;
}

void destructor(struct fengzhuang *f) //删除封装了的结构体
{
 free(f->base);
}
#endif
/*思想为结构体的内存布局,即结构体内每个域的内存位置是按照定义的顺序从低地址往高地址顺序存放的*/
#ifdef Duotai
/*获得结构体中的内部对象*/
#define offset_of(type,number) \
 ((unsigned long) (&((type *)0)->number))

#define container_of(ptr,type,number) \
 ((type *)((unsigned long)(ptr)-offset_of(type,number)))

/*主类型*/
struct shape {
 char *name;
 struct shape_operations * opt;
};
struct shape_operations {
 void (*Draw)(struct shape *);
};

/*三角形*/
struct triangle {
 int a,b,c;
 struct shape base;
};

static void draw_triangle(struct shape *t)
{
 struct triangle* self = container_of(t,struct triangle,base);
 printf("draw a %s: %d\t%d\t%d\n", t->name, self->a, self->b, self->c);
}

static struct shape_operations triangle_operations = {
 draw_triangle,
};

void triangle_constructor(struct triangle * t,int a,int b,int c)
{
 t->a=(a>0) ? a : 1;
 t->b=(b>0) ? b : 1;
 t->c=(c>0) ? c : 1;
 t->base.name = "triangle";
 t->base.opt = &triangle_operations;
}

/*正方形*/
struct square {
    int e;
    struct shape base;
};
 
static void draw_square(struct shape* s)
{
    struct square* self = container_of(s, struct square, base);
    printf("draw a %s: e = %d\n", s->name, self->e);
}
 
static struct shape_operations square_operations = {
    draw_square,
};
 
void square_constructor(struct square* s, int e)
{
    s->e = (e > 0) ? e : 1;
    s->base.name = "square";
    s->base.opt = &square_operations;
}
/*输出函数*/
void DrawShape(struct shape * s)
{
 s->opt->Draw(s);
}
#endif

 

测试:

int main()
{
 triangle t;
 triangle_constructor(&t,2,2,2);
 DrawShape(&t.base);
 square s;
 square_constructor(&s,4);
 DrawShape(&s.base);
 return 0;
}


 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值