Shapes-Ojbect3

来源:互联网 发布:软件测试费发票 编辑:程序博客网 时间:2024/06/01 08:50

继续修改前面的代码,最终修改结果如下:

////  main.m//  Shapes-Object////  Created by cloud on 13-3-7.//  Copyright (c) 2013年 cloud. All rights reserved.//#import <Foundation/Foundation.h>typedef enum {    kRedColor,    kGreenColor,    kBlueColor} ShapeColor;typedef struct {    int x,y,width,height;} ShapeRect;NSString *colorName(ShapeColor color){    switch (color) {        case kRedColor:            return @"red";            break;        case kGreenColor:            return @"green";            break;        case kBlueColor:            return @"blue";            break;        default:            return @"no clue";            break;    }}@interface Shape : NSObject{    ShapeColor fillColor;    ShapeRect   bounds;}@end@implementation Shape-(void) setFillColor:(ShapeColor)c{    fillColor=c;}-(void) setBounds:(ShapeRect)b{    bounds=b;}-(void) draw{   }@end@interface Circle :Shape{}@end@implementation Circle-(void) draw{    NSLog(@"drawing a circle at(%d %d %d %d) in %@",bounds.x,bounds.y,bounds.width,bounds.height,colorName(fillColor));}@end@interface Rectangle : Shape{}@end@implementation Rectangle-(void) draw{    NSLog(@"drawing a rectangle at(%d %d %d %d) in %@",bounds.x,bounds.y,bounds.width,bounds.height,colorName(fillColor));}@end@interface OblateSphereoid : Shape{    }@end@implementation OblateSphereoid-(void) draw{    NSLog(@"drawing an egg at(%d %d %d %d) in %@",bounds.x,bounds.y,bounds.width,bounds.height,colorName(fillColor));}@end@interface Triangle : Shape{}@end@implementation Triangle-(void) draw{    NSLog(@"drawing a triangle at(%d %d %d %d) in %@",bounds.x,bounds.y,bounds.width,bounds.height,colorName(fillColor));}@endvoid drawShapes(id shapes[],int count){    int i;    for(i=0;i<count;i++)    {        id shape= shapes[i];        [shape draw];    }}int main(int argc, const char * argv[]){    //@autoreleasepool {            id shapes[4];                ShapeRect rect0={0,0,10,30};        shapes[0]=[Circle new];            [shapes[0] setBounds:rect0];        [shapes[0] setFillColor:kRedColor];                ShapeRect rect1={30,40,50,60};        shapes[1]=[Rectangle new];        [shapes[1] setBounds:rect1];        [shapes[1] setFillColor:kGreenColor];                ShapeRect rect2={15,19,37,29};        shapes[2]=[OblateSphereoid new];        [shapes[2] setBounds:rect2];        [shapes[2] setFillColor:kBlueColor];            ShapeRect rect3={47,32,80,50};        shapes[3]=[Triangle new];        [shapes[3] setBounds:rect3];        [shapes[3] setFillColor:kRedColor];            drawShapes(shapes, 4);           // }    return 0;}
运行结果如下:

objective-c的继承与C++没有太大的区别,不过要注意,它只能有一人父类,是单继承。