object-c 学习(面向对象)

main.m
extern void drawshape(__strong id shape[],int num);

int main(int argc, const char * argv[])
{
    id shape[3];   //创建一个数组,存放具体的图形对象
    ShapEgg *egg = [[ShapEgg alloc]init]; //对象的初始化,先分配内存,在调用init方法初始化
    //把egg对象赋给shape数组的第一个元素
    shape[0] = egg;
    //创建一个circle对象
    Circle *circle = [[Circle alloc]init];
    shape[1] = circle;
    Rectangle *rectangle = [[Rectangle alloc]init];
    shape[2] = rectangle;
    
    drawshape(shape,3);
    return 0
}

void drawshape(__strong id shape[],int num)   
{
    for(int i = 0; i < num; i++)
    {
        [shape[i] draw];
    }
}

定义一个Circle类

@interface Circle : NSObject
{
ShapColor fillColor;    //  定义成员变量或者实例变量
ShapRect bounds;
}

-(Circle *)init;     //对象方法(重构init方法)
-(void)draw;

@end    //end of Circle


实现代码

@implementation Circle

-(Circle *)init
{
    if (self = [super init]) {    //super
        ShapRect rect = {1,32,35,56};
        bounds = rect;
        fillColor = kRedColor;
    }
    return self;
}
-(void)draw
{
    NSLog(@"Circle is draw at (%d,%d,%d,%d) in %@",bounds.x,bounds.y,bounds.width,bounds.height,[self colorName:fillColor]); 

}

-(NSString *)colorName:(ShapColor)color    //circle的私有方法(其他对象不能访问)
{
    NSString *colorName = nil;
    switch (color) {
        case kRedColor:
            colorName = @"Red";
            break;
        case kBlueColor:
            colorName = @"Blue";
            break;
        case kGreenColor:
            colorName  = @"Green";
            break;    
        default:
            break;
    }
    return colorName;

}
@end

补充:

      1.方法前的加减号为:减号为实例化对象的方法,加号是类的方法 

      2.实例是对的对象的另一种说法

      3.对象是一种包含值和指向其来得隐藏指针的结构体

     4.消息是对象要执行的操作

      5.过程式程序建立在函数之上,数据为函数服务;面向对象的思想是以程序的数据为中心。函数为数据服务。在OOP中,不再重点关注程序中的数据,而是专注于数据

(狗为一个类的话,那么我家的兜兜(金毛)就是一个对象,会叫就是他的方法,我发送一个消息叫她叫,她就叫了)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章