Objective-c自学笔记(1)-类

今天是2015年1月19日,今天学习了类的定义。虽然很简单,但是希望是个好的开始。纪录如下:


类的接口


Circle.h

#import <Foundation/Foundation.h>
//定义枚举来描述可用的选项
typedef enum{
    KCircle,KRectangle,KEgg
}SHapeType;
typedef enum{
    KRedColor,
    KGreenColor,
    KBlueColor
}ShapeColor;
//使用结构体描述举行
typedef struct{
    int x,y,heigth,width;
}ShapeRect;
typedef struct{
    SHapeType type;
    ShapeColor fillColor;
    ShapeRect bounds;
}Shape;

@interface QHCircle : NSObject
{
@private
    ShapeColor fillColor;
    ShapeRect bounds;
}
-(void)setFillColor:(ShapeColor)fillColor;
-(void)setBounds:(ShapeRect)bounds;
-(void)draw;
@end//Circle

类的实现


#import "QHCircle.h"

@implementation QHCircle
-(void)setFillColor:(ShapeColor)c{
    fillColor = c;
}//setFillColor
-(void)setBounds:(ShapeRect)b{
    bounds = b;
}//setBounds
-(void)draw{
    NSLog(@"drawing a circle at (%d %d %d %d)",bounds.x,bounds.y,bounds.width,bounds.heigth);
}//draw
@end//Circle

测试


#import "QHCircle.h"
int main(int argc,char *argv[]){
    @autoreleasepool {
        NSLog(@"Hello,world!");
        //初始化一个Shape数组,大小为1
        id shapes[1];
        //创建一个Circle对象
        ShapeRect rect0 = {0,0,30,40};
        shapes[0] = [QHCircle new];
        [shapes[0] setBounds:rect0];
        [shapes[0] setFillColor:KRedColor];
        [shapes[0] draw];
        return (0);
    }
    
}//main

输出:


2015-01-19 23:00:06.461 Helloworld[5868:45375] Hello,world!
2015-01-19 23:00:06.463 Helloworld[5868:45375] drawing a circle at (0 0 40 30)
Program ended with exit code: 0


你可能感兴趣的:(ios)