Objective-C中的类学习第一篇(补)

昨天写的类学习第一篇中还有一些基础内容需要做一些补充:

首先是关于如何合理的设计一个简单的类。

附上一段自己练手的学生遛狗的代码:

#import<Foundation/Foundation.h>

//性别

typedef enum{

    SexMan,

    SexWoman

} Sex;

//日期

typedef struct {

    int year;

    int month;

    int day;

} Date;

//颜色

typedef enum {

    ColorBlack,

    ColorRed,

    ColorGreen

}Color;


/*

 

 成员变量:体重,毛色

 方法:吃,跑

 */

@interface Dog : NSObject

{

    @public

    double weight;

    Color curColor;

}

- (void) run;

- (void) eat;

@end


@implementation Dog


- (void) run

{

    weight -= 1;

    NSLog(@"狗跑完这次后的体重是%f",weight);

}

- (void) eat

{

    weight += 1;//每吃一次,体重加一

    NSLog(@"狗吃完这次后的体重是%f",weight);

}

@end

/*

 学生

 成员变量:性别,生日,体重,最喜欢的颜色,狗

 方法:吃,跑步,遛狗(让狗跑),喂狗(让狗吃)

 */

@interface Student : NSObject

{

    @public

    char* name;//姓名

    Sex sex;//性别

    Date birthday;//生日

    double weight;//体重(kg

    Color favColor;//最喜欢的颜色

    Dog *dog;//

}

- (void) run;

- (void) eat;

- (void) print;//学生的基本信息

- (void) LiuDog;//遛狗

- (void) WeiDog;//喂狗

@end


@implementation Student

- (void) run

{

    weight -= 1;

    NSLog(@"学生跑完这次后的体重是%f",weight);

}

- (void) eat

{

    weight += 1;//每吃一次,体重加一

    NSLog(@"学生吃完这次后的体重是%f",weight);

}

-(void) print

{

    NSLog(@"性别 = %d,喜欢的颜色 = %d,姓名 = %s,生日 = %d-%d-%d",sex,favColor,name,birthday.year,birthday.month,birthday.day);

}


- (void) LiuDog

{

    //调用狗的run方法

    [dog run];

}

- (void) WeiDog

{

    //调用狗的eat方法

    [dog eat];

}

@end


int main()

{

    Student *s = [Student new];


    Dog *dog = [Dog new];

    dog->curColor = ColorRed;

    dog->weight = 20;


    s->dog = dog;

    s->weight = 50;

    

    //姓名

    s->name = "Jack";

    //性别

    s->sex = SexMan;

    //生日

    //s->birthday = {2011,9,10};

    Date d = {2011,9,10};

    s->birthday = d;

    //喜欢颜色

    s->favColor = ColorBlack;

    

    [s eat];

    [s run];

    [s print];

    

    [s LiuDog];//遛狗

    [s WeiDog];//喂狗

    return 0;

}


其次要补充的是方法的一些基本知识和注意事项,下面以一个计算器类来做个简单说明:

#import<Foundation/Foundation.h>

/*

 计算器类

 方法:

 1> 返回 π

 2> 计算某个整数的平方

 3> 计算两个整数的和

 */

@interface JiSuanQi : NSObject


//方法名:pi

- (double) pi;


//OC方法中一个参数对应一个冒号

//方法名:pingFang:(冒号也是方法名的一部分)

- (int) pingFang:(int)num;


//- (int)Sum:(int)a :(int)b;

//在每个冒号前加上一些描述信息;

//方法名:SumWithNum1:andNum2:

- (int)SumWithNum1:(int)num1 andNum2:(int)num2;


@end


@implementation JiSuanQi


- (double) pi

{

    return 3.14;

}

-(int) pingFang:(int)num

{

    return num * num;

}

- (int)SumWithNum1:(int)num1 andNum2:(int)num2

{

    return num1 + num2;

}


@end


int main()

{

    JiSuanQi *jsq = [JiSuanQi new];

    

    double a = [jsq pi];

    NSLog(@"%f",a);

    

    int b = [jsq pingFang:10];

    NSLog(@"%d",b);

    

    int c = [jsq SumWithNum1:10 andNum2:5];

    NSLog(@"%d",c);

    return 0;

}


posted @ 2015-01-18 22:40  SarielTang  阅读(109)  评论(0编辑  收藏  举报