2008年2月26日 星期二

C

C語言是一個很有彈性的程式語言
可以繁複,可以簡約
可以華麗,可以樸實
可以高階,可以低階
實在很佩服設計這個語言的人
讓我讚嘆不已

今天稍微嘗試一下簡單OOP in C, sweet

[ common.h ]
#ifndef COMMON_H
#define COMMON_H

#define SHAPE int X;\
int Y;\
void (*Draw)( struct Shape* );

typedef struct Shape {
SHAPE;
} Shape;

typedef struct Circle {
SHAPE;
int radius;
void (*SetRadius)( struct Circle* , int);
} Circle;
Circle* New_Circle( int );

typedef struct Square {
SHAPE;
int Xdim;
int Ydim;
void (*SetDimension)( struct Square* ,int, int );
} Square;
Square* New_Square( int, int );

#endif


[ circle.c ]
#include "common.h"

static void Draw( struct Shape* shape )
{
Circle *circle = ( Circle * ) shape;

printf( "drawing a circle, radius : %d \n", circle -> radius );
}

void SetRadius(struct Circle* c, int r )
{
c -> radius = r;
}

Circle* New_Circle(int r)
{
Circle *circle = ( Circle* ) malloc( sizeof(Circle) );
circle -> radius = r;
circle -> SetRadius = SetRadius;
circle -> Draw = Draw;
return circle;
}

[square.c]
#include "common.h"

static void Draw( struct Shape* shape )
{
Square* sq = (Square*) shape;

printf( "dwawing a square, area:%d\n" , ( sq->Xdim * sq->Ydim ) );

}

void SetDimension( struct Square* sq,int X, int Y)
{
sq -> Xdim = X;
sq -> Ydim = Y;
}

Square* New_Square( int Xdim, int Ydim)
{
Square* sq = ( Square* ) malloc( sizeof( Square ) );
sq -> Xdim = Xdim;
sq -> Ydim = Ydim;
sq -> Draw = Draw;
sq -> SetDimension = SetDimension;
return sq;
}

[ main.c]
int main()
{
Shape* shapeCollection[ 3 ];
shapeCollection[ 0 ] = (Shape*) New_Circle( 10 );
shapeCollection[ 1 ] = (Shape*) New_Square( 4, 3 );
shapeCollection[ 2 ] = (Shape*) New_Circle( 3 );

int i;
for( i = 0; i < 3; ++i )
shapeCollection -> Draw( shapeCollection[ i ] );


return 0;
}

[ output ]
drawing a circle, radius : 10
dwawing a square, area:12
drawing a circle, radius : 3

沒有留言: