//内存管理类new.h
#ifndef NEW_H
#define NEW_H
void
*
new
(
const
void
*
class
, ...);
void
delete
(
void
* item);
void
draw (
const
void
* self);
#endif
//内存管理类的C文件:new.c
#include “new.h”
#include “base.h”
void
*
new
(
const
void
* _base, ...)
{
const
struct
Base * base = _base;
void
* p =
calloc
(1, base->size);
assert
(p);
* (
const
struct
Base **) p = base;
if
(base ->ctor)
{
va_list
ap;
va_start
(ap, _base);
p = base ->ctor(p, &ap);
va_end
(ap);
}
return
p;
}
void
delete
(
void
* self)
{
const
struct
Base ** cp = self;
if
(self && * cp && (* cp) —> dtor)
self = (* cp) —>dtor(self);
free
(self);
}
void
draw (
const
void
* self)
{
const
struct
Base *
const
* cp = self;
assert
(self &&* cp && (* cp)->draw);
(* cp) ->draw(self);
}
//基类:base.h
#ifndef BASE_H
#define BASE_H
struct
Base
{
size_t
size;
//类所占空间
void
* (* ctor) (
void
* self,
va_list
* app);
//构造函数
void
* (* dtor) (
void
* self);
//析构函数
void
(* draw) (
const
void
* self);
//作图
};
#endif
//Point头文件(对外提供的接口):point.h
#ifndef POINT_H
#define POINT_H
extern
const
void
* Point;
/* 使用方法:new (Point, x, y); */
#endif
//Point内部头文件(外面看不到):point.r
#ifndef POINT_R
#define POINT_R
struct
Point
{
const
void
* base;
//继承,基类指针,放在第一个位置,const是防止修改
int
x, y;
//坐标
};
#endif
//Point的C文件:point.c
#include “point.h”
#include “new.h”
#include “point.h”
#include “point.r”
static
void
* Point_ctor (
void
* _self,
va_list
* app)
{
struct
Point * self = _self;
self ->x =
va_arg
(* app,
int
);
self ->y =
va_arg
(* app,
int
);
return
self;
}
static
void
Point_draw (
const
void
* _self)
{
const
struct
Point * self = _self;
printf
(“draw (%d,%d)”, self -> x, self -> y);
}
static
const
struct
Base _Point = {
sizeof
(
struct
Point), Point_ctor, 0, Point_draw
};
const
void
* Point = & _Point;
//测试程序:main.c
#include “point.h”
#include “new.h”
int
main (
int
argc,
char
** argv)
{
void
* p =
new
(Point, 1, 2);
draw(p);
delete
(p);
}
联系客服