上一篇中,所有代码都是放在同一个文件main.h中的,这显然不是一个好的方式,代码多了以后,看着就头大。可以将其进行拆分:
1、将所有枚举、结构的定义单独放在一个文件ShapeDef.h中
//定义“几何形状类型”枚举typedef enum{ kCircle, kRectangle, kOblatesShperoid } ShapeType; //定义“几何形状颜色”枚举typedef enum{ kRedColor, kGreenColor, kBlueColor} ShapeColor; //定义“几何形状矩形区域”结构typedef struct{ int x,y,width,height;} ShapeRect; //定义“几何形状”结构typedef struct{ ShapeType type; ShapeColor fillColor; ShapeRect bounds;}Shape;
2、将所有方法都放在另一个文件ShapeMethod.h中
#import "ShapeDef.h"//将“颜色枚举“转换为字符串NSString *colorName(ShapeColor colorName){ switch (colorName) { case kRedColor: return @"red"; break; case kGreenColor: return @"green"; break; case kBlueColor: return @"blue"; default: return @"no clue"; break; }}//画圆void drawCircle(ShapeRect bounds,ShapeColor fillColor){ NSLog(@"drawing a circle at (%d,%d,%d,%d) in %@",bounds.x,bounds.y,bounds.width,bounds.height,colorName(fillColor));}//drawCircle //画矩形void drawRectangle(ShapeRect bounds,ShapeColor fillColor){ NSLog(@"drawing a rectangle at (%d,%d,%d,%d) in %@",bounds.x,bounds.y,bounds.width,bounds.height,colorName(fillColor));}//drawRectangle //画椭圆形void drawEgg(ShapeRect bounds,ShapeColor fillColor){ NSLog(@"drawing an egg at (%d,%d,%d,%d) in %@",bounds.x,bounds.y,bounds.width,bounds.height,colorName(fillColor));}//drawEgg //画几何形状void drawShapes(Shape shapes[],int count){ int i; for(i=0;i<count;i++) { switch (shapes[i].type) { case kCircle: drawCircle(shapes[i].bounds,shapes[i].fillColor); break; case kRectangle: drawRectangle(shapes[i].bounds,shapes[i].fillColor); break; case kOblatesShperoid: drawEgg(shapes[i].bounds,shapes[i].fillColor); break; default: break; } }}//drawShapes
3、最后在主文件Main.m中使用ShapeMethod.h
#import "ShapeMethod.h"int main () { Shape shapes[3]; ShapeRect rect0 ={0,0,10,30}; shapes[0].type = kCircle; shapes[0].fillColor = kRedColor; shapes[0].bounds = rect0; ShapeRect rect1 = {30,40,50,60}; shapes[1].type = kRectangle; shapes[1].fillColor = kGreenColor; shapes[1].bounds = rect1; ShapeRect rect2 = {15,18,37,39}; shapes[2].type = kOblatesShperoid; shapes[2].fillColor = kBlueColor; shapes[2].bounds = rect2; drawShapes(shapes, 3); return 0;}
注:ShapeDef.h,ShapeMethod.h,Main.m三个文件均处于同一个项目的同一个目录中。
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦