您的位置:首页 > 职场人生

黑马程序员——对象与函数

2015-08-11 20:56 561 查看
------<a href="http://www.itheima.com" target="blank">Java培训、Android培训、iOS培训、.Net培训</a>、期待与您交流! -------

1、类的合理设计
typedef enum{
SexMan;
SexWoman;
}Sex;

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

tyedef enum{
ColorBlack;
ColorRed;
ColorGreen;
}Color;

//学生
//成员变量:性别、生日、体重、最喜欢的颜色、狗
//方法:吃、跑、遛狗、喂狗

#inport<Foundation/Foundation.h>
//声明
@interface Student :NSObject
{
//声明对象属性
@public
Sex sex;
Date birthday;
double weight;
Color favCoolor;
char *name;
}

-(void)eat;
-(void)run;
-(void)liudog;
-(void)weidog;
-(void)print;
@end

@interface Dog :NSObject
{
//声明对象属性
@public
double weight;
Color curColor;
}

-(void)eat;
-(void)run;
@end

@implementation Car
//方法的实现
-(void)eat
{
weight + = 1;
NSLog(@"吃完这次的体重是:%f",weight);
}
-(void)run
{
weight - = 1;
NSLog(@"跑完这次的体重是:%f",weight);
}

@end

//实现
@implementation Student
//方法的实现
-(void)eat
{
weight + = 1;
NSLog(@"吃完这次的体重是:%f",weight);
}
-(void)run
{
weight - = 1;
NSLog(@"跑完这次的体重是:%f",weight);
}

-(void)liudog
{
[dog run];
}
-(void)weidog
{
[dog eat];
}

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

@end

int main()
{
Student *s = [Student new];
s->weight = 50;
[s eat];
[s eat];
[s run];
[s run];
}

输出结果:吃完这次的体重是:51

   吃完这次的体重是:52

   跑完这次的体重是:51

   跑完这次的体重是:50

将main()函数改为:

int main()
{
Student *s = [Student new];
s->weight = 50;
s->sex = SexMan;
s->name = "Jack"
Date d = {2011,3,21};
s->birthday = d;
[s print];
}

输出结果:性别 = 0,喜欢的的颜色 = 0,姓名 = Jack,生日 = 2011-3-21

将main()函数改为:

int main()

{

 Student *s = [Student new];

 Dog *d = [Dog new];

 d->weight = 20;

 d->curColor = ClorGreen;

 s->dog = d;

 [s liuDog];

 [s weiDog];

}

输出结果:跑完这次的体重是:19.00

  吃完这次的体重是:20.00

总结:

    对象方法都是以减号-开头,不能独立于类存在。

    对象方法的声明必须写在@interface与@end之间

    对象方法的实现必须写在@implementation与@end之间

    对象方法只能由对象来调用

    函数能写在文件中的任意位置(除了@interface与@end之间),函数归文件所有

    函数调用不依赖于对象

    函数你不不能直接通过成员变量名访问某个对象的成员变量

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: