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

------<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之间),函数归文件所有
    函数调用不依赖于对象
    函数你不不能直接通过成员变量名访问某个对象的成员变量


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值