对象方法

2016-01-09  本文已影响21人  MarkTang
//
//  main.m
//  第一个对象方法
//
//  Created by zyz on 15/12/7.
//  Copyright (c) 2015年 zyz. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface Person : NSObject
{
    //因为默认对象是@protected要改变为@public
    @public
    NSString *_name;
    int _age;
    int _weight;

}

//介绍  类型用()括起来,没有参数的话后面就不用写
//没有返回值没有参数
-(void)introduce;
//没有返回值有参数
-(void)walkWithMetre:(int)metre;
//有返回值没有参数
-(int)eat;
//有返回值有参数
-(int)finghtWithName:(NSString *)name;
@end
@implementation Person
//对象方法实现名字必须和申明是名字一致 对象方法内可以直接调用成员属性
-(void)introduce
{
    NSLog(@"我叫%@,我今年%i岁,体重%i",_name,_age,_weight);

}
//在参数前面最好加上标签 和冒号
-(void)walkWithMetre:(int)metre
{
    
    NSLog(@"我走了%i米",metre);
}
-(int)eat
{
    
    return 15;
}
-(int)finghtWithName:(NSString *)name
{
    NSLog(@"和%@打了一架",name);
    return 1;
}
@end
int main(int argc, const char * argv[]) {
   //首先创建一个对象
    Person *p  = [Person new];
    //修改属性
    p->_name = @"zyz";
    p->_age = 21;
    p->_weight = 114;
    
    //调用方法就是给这个对象发送消息
    [p introduce];
    [p walkWithMetre:15];
     int eat = [p eat];
    NSLog(@"我吃了%i碗饭",eat);
    [p finghtWithName:@"曾亚洲"];
    return 0;
}
上一篇 下一篇

猜你喜欢

热点阅读