黑马程序员技术交流社区
标题:
看到OC里的那个对象嵌套,有点蒙,谁给讲解一下
[打印本页]
作者:
young_star
时间:
2014-12-12 12:13
标题:
看到OC里的那个对象嵌套,有点蒙,谁给讲解一下
重点是关于学生的狗的那块,有点不懂,怎么定义和实现的
#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)eat;
- (void)run;
@end
@implementation Dog
- (void)eat
{
// 每吃一次,体重就加1
weight += 1;
//weight = weight + 1;
NSLog(@"狗吃完这次后的体重是%f", weight);
}
- (void)run
{
weight -= 1;
NSLog(@"狗跑完这次后的体重是%f", weight);
}
@end
/*
学生
成员变量:性别、生日、体重、最喜欢的颜色、狗(体重、毛色,吃、跑)
方法:吃、跑步、遛狗(让狗跑)、喂狗(让狗吃)
*/
@interface Student : NSObject
{
@public
Sex sex; // 性别
Date birthday; // 生日
double weight; // 体重(kg)
Color favColor; // 最喜欢的颜色
char *name;
// 重点:狗
Dog *dog;
}
- (void)eat;
- (void)run;
- (void)print;
- (void)liuDog;
- (void)weiDog;
@end
@implementation Student
- (void)liuDog
{
// 让狗跑起来(调用狗的run方法)
[dog run];
}
- (void)weiDog
{
// 让狗吃东西(调用狗的eat方法)
[dog eat];
}
- (void)print
{
NSLog(@"性别=%d, 喜欢的颜色=%d, 姓名=%s, 生日=%d-%d-%d", sex, favColor, name, birthday.year, birthday.month, birthday.day);
}
- (void)eat
{
// 每吃一次,体重就加1
weight += 1;
//weight = weight + 1;
NSLog(@"学生吃完这次后的体重是%f", weight);
}
- (void)run
{
weight -= 1;
NSLog(@"学生跑完这次后的体重是%f", weight);
}
@end
int main()
{
Student *s = [Student new];
Dog *d = [Dog new];
d->curColor = ColorGreen;
d->weight = 20;
s->dog = d;
[s liuDog];
[s weiDog];
return 0;
}
void test()
{
Student *s = [Student new];
s->weight = 50;
// 性别
s->sex = SexMan;
// 生日
Date d = {2011, 9, 10};
s->birthday = d;
s->name = "Jack";
/*
s->birthday.year = 2011;
s->birthday.month = 9;
s->birthday.day = 10;
*/
// 喜欢的颜色
s->favColor = ColorBlack;
/*
[s eat];
[s eat];
[s run];
[s run];
*/
[s print];
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2