跟着视频敲出来的,理解以后敲几遍。有助于体会面向对象的真谛。代码如下:
#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;
}
|