我倒是不追求代码和C++相似,但是应该追求简洁的代码,下面是一个新的尝试
shape.h
#ifndef SHAPE_H #define SHAPE_H typedef struct shape_t { void *shapeData; void (*area)(void *); void (*release)(void *); }Shape; void release(void *shape); #endif
shape.c
#include <stdlib.h> #include "shape.h" void release(void *shape) { free(((Shape*)shape)->shapeData); free(shape); }
circle.h
#ifndef CIRCLE_H #define CIRCLE_H #include "shape.h" typedef struct { double r; }Circle; Shape* makeCircle(double r); #endif
circle.c
#include <assert.h> #include <stdlib.h> #include <stdio.h> #include "shape.h" #include "circle.h" const double PI = 3.14159; static void area(void *shape) { Circle *_circle = (Circle*)((Shape *)shape)->shapeData; printf("the circle area is %f ", _circle->r * _circle->r * PI); } Shape* makeCircle(double r) { Shape *shape = (Shape *)malloc(sizeof(Shape)); Circle *circle = (Circle *)malloc(sizeof(Circle)); assert(shape != NULL && circle != NULL); assert(r > 0); circle->r = r; shape->shapeData = circle; shape->area = &area; shape->release = &release; return shape; }
rectange.h
#ifndef RECTANGLE_H #define RECTANGLE_H typedef struct{ float x; float y; }Rectangle; Shape *makeRectangle(float x, float y); #endif
rectange.c
#include <assert.h> #include <stdlib.h> #include <stdio.h> #include "shape.h" #include "rectangle.h" static void area(void *shape) { Rectangle *rectangle = (Rectangle*)((Shape *)shape)->shapeData; printf("the rectangle area is %f ", rectangle->x * rectangle->y); } Shape* makeRectangle(float x, float y) { Shape *shape = (Shape *)malloc(sizeof(Shape)); Rectangle *rectangle = (Rectangle *)malloc(sizeof(Rectangle)); assert(shape != NULL && rectangle != NULL); assert(x > 0 && y > 0); rectangle->x = x; rectangle->y = y; shape->shapeData = rectangle; shape->area = &area; shape->release = &release; return shape; }
main.c
#include <stdio.h> #include "shape.h" #include "circle.h" #include "rectangle.h" void printShapeArea(Shape **shapes,int length) { int i=0; for(i=0;i<length;i++) { Shape *shape = shapes[i]; shape->area(shape); shape->release(shape); } } int main() { Shape *p[3] = {makeCircle(3.2),makeCircle(3.2),makeRectangle(3,4)}; printShapeArea(p,3); return 0; }