黑马程序员技术交流社区

标题: OC面向对象-经典习题《人遛狗、喂狗》,用这个练习!!! [打印本页]

作者: 蜗牛快跑    时间: 2014-10-14 18:25
标题: OC面向对象-经典习题《人遛狗、喂狗》,用这个练习!!!
跟着视频敲出来的,理解以后敲几遍。有助于体会面向对象的真谛。代码如下:
#import <Foundation/Foundation.h>
typedef enum
{
        ColorBlack,
        ColorRed,
        ColorBlue
}Color;

typedef struct
{
        int year;
        int month;
        int day;
}Date;

typedef enm
{
        SexMan,
        SexWomen
}Sex;

@interface Dog:NSObject
{
        @public
        double weight;
        Color curColor;
}
- (void)run;
- (void)eat;
@end

@implementation Dog
- (void)run
{
        weight -= 1;
        NSLog(@"狗跑完这圈以后我的体重是%f.2",weight);
}

- (void)eat
{
        weight += 1;
        NSLog(@"狗吃完这顿以后我的体重是%f.2",weight);
}
@end

@interface Person:NSObject
{
        @public
        Sex sex;
        int weight;
        Date birthday;
        Color favColor;
        char *name;
        Dog *dog;
       
}
- (void)run;
- (void)eat;
- (void)print;
- (void)liuDog;
- (void)weiDog;
@end

@implementation Person
- (void)run
{
        weight -= 1;
        NSLog(@"跑完这圈以后我的体重是%f.2",weight);
}

- (void)eat
{
        weight += 1;
        NSLog(@"吃完这顿以后我的体重是%f.2",weight);
}

- (void)print
{
        NSLog(@"%d,%d,%s,%d-%d-%d",sex,favColor,name,birthday.year,birthday.month,birthday.day);
}

- (void)liuDog
{
        [dog run];
}
- (void)weiDog
{
        [dog eat];
}
@end

int main()
{
        Person *p = [Person new];
        Dog *dog2 = [Dog new];
        dog2->weight = 20;
        dog2->curColor = ColorRed;
        p->dog = dog2;
        p->weight = 50;
        p->sex = SexMan;
        p->favColor = ColorBlack;
        Date d = {2014,10,14};
        p->birthday = d;
        s->name = "jack";

        [p run];
        [p run];
        [p eat];
        [p eat];
        [p print];

        [p liuDog];
        [p weiDog];
        return 0;
}





作者: 米匠    时间: 2014-10-14 20:27
好帖。。。。。感谢分享,学习了
作者: 杰克船长    时间: 2014-10-16 10:16
居然没看懂




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2