typedef enum{
SexMan,
SexWomen
} Sex;
typedef struct{
int year;
int month;
int day;
} Date;
typedef enum{
ColorBule,
ColorBlack,
ColorRed
} Color;
typedef enum{
DogColorBule,
DogColorBlack,
DogColorRed
}DogColor;
#import <Foundation/Foundation.h>
@interface Dog:NSObject
{
@public
DogColor DogCol;
int DogWeight;
}
-(void)DogRun;
-(void)DogEat;
-(void)DogMessage;
@end
@implementation Dog
-(void)DogRun
{
DogWeight-=1;
NSLog(@"狗跑完这次的体重是%d",DogWeight);
}
-(void)DogEat
{
DogWeight+=1;
NSLog(@"狗跑完这次的体重是%d",DogWeight);
}
-(void)DogMessage
{
NSLog(@"狗的颜色是%d,狗的体重是%d",DogCol,DogWeight);
}
@end
@interface Student:NSObject
{
@public
Sex sex;
Date birthday;
int weight;
Color favColor;
Dog *dog;
}
-(void)eat;
-(void)run;
-(void)liugou;
-(void)weigou;
-(void)Message;
@end
@implementation Student
-(void)eat
{
weight+=1;
//NSLog(@"一个生日是%d,体重是%d,喜欢%s颜色的%s同学在吃饭",birthday,weight,color,sex);
NSLog(@"吃完这次体重是%d",weight);
}
-(void)run
{
weight-=1;
NSLog(@"跑完这次体重是%d",weight);
}
-(void)liugou
{
[dog DogRun];
}
-(void)weigou
{
[dog DogEat];
}
-(void)Message
{
NSLog(@"该学生的性别是%d,生日是%d-%d-%d,体重是%d,最喜欢的颜色是%d",sex,birthday.year,birthday.month,birthday.day,weight,favColor);
}
-(void)DogMess
{
[dog DogMessage];
}
@end
void DogAction(Student *who)
{
Dog *d=[Dog new];
//S->dog->DogCol=DogColorBlack; 错误,指针指向错误,指向的是类型,不是实例对象
//S->dog->DogWeight=40; 错误,指针指向错误,指向的是类型,不是实例对象
d->DogWeight=40;
d->DogCol=DogColorRed;
who->dog=d;
[who liugou];
[who weigou];
[who DogMess];
//[who Message]; //验证是这个学生的狗
}
int main()
{
Student *S=[Student new]; //创建一个学生的对象
S->weight=50;
S->sex=SexWomen;
Date D={2001,07,10}; //初始化一个Date类型取名为D,并赋值
S->birthday=D;
S->favColor=ColorBule;
[S eat];
[S Message];
DogAction(S); //调用狗的行为的函数,告知是这个学生的狗
return 0;
}
-----------------------------------------------------
上述程序运行结果:
MacdeMacBook-Pro:Test mac$ cc 09-OC类的设计练习.m -framework Foundation
MacdeMacBook-Pro:Test mac$ ./a.out
2014-04-24 17:22:10.008 a.out[1041:507] 吃完这次体重是51
2014-04-24 17:22:10.010 a.out[1041:507] 该学生的性别是1,生日是2001-7-10,体重是51,最喜欢的颜色是0
2014-04-24 17:22:10.011 a.out[1041:507] 狗跑完这次的体重是39
2014-04-24 17:22:10.011 a.out[1041:507] 狗跑完这次的体重是40
2014-04-24 17:22:10.012 a.out[1041:507] 狗的颜色是2,狗的体重是40
-----------------------------------------------------
总结:
1> 指针必须指向的是实例
例: 上述代码中
Dog *d=[Dog new];
//S->dog->DogCol=DogColorBlack; 错误,指针指向错误,指向的是类型,不是实例对象
//S->dog->DogWeight=40; 错误,指针指向错误,指向的是类型,不是实例对象
实例化了一个Dog,但是并没有通过指针修改这个实例化的Dog的参数,而是直接修改类的定义中定义的另一个类的行参
2> 无法直接跨对象调用类中对象的方法
例: Student *S=[Student new];
// [S DogEat]; 这样写是错误的,学生类里面并没有DogEat的方法。
Dog D=[Dog new];
S->dog=D;
[S->dog DogEat]; 可以实例化一个Dog赋给S中的Dog对象,再这样执行这个方法。
|
|