OC 类方法 对象方法 对象成员之间的关系



#import <Foundation/Foundation.h>

@interface Person : NSObject
{
    int _age; // 年龄
    float _height; // 身高
}

/*
 特征: 用类名来调用的方法, 不需要创建对象, 主要用来表达类相关信息
 语法:
  类方法 以 + 号开头, 其它特征与对象方法相同
*/
+ (void)showClassName; // 打印类名

- (void)setAge: (int)age;

- (void)setHeight: (float)height;

- (void)showInfo;
@end



int main()
{
    
    Person *xiaomi = [Person new];
    Person *kupai = [Person new];
    
    [Person showClassName]; // 用类名调用类方法
    
    
    [xiaomi setAge:3];
    [xiaomi setHeight:1.7];
    
    [kupai setAge:5];
    [kupai setHeight:1.85];
    
    [xiaomi showInfo];
    [kupai showInfo];
    
    // [xiaomi showClassName]; 类方法只能由类名调用,不可以用对象名调用
    
    return 0;
}



@implementation Person

+ (void)showClassName
{
    NSLog(@"Class name: Person ");
}
- (void)setAge: (int)age
{
    _age = age;
}

- (void)setHeight: (float)height
{
    _height = height;
}

- (void)showInfo
{
    NSLog(@"年龄是 %i   身高是: %f", _age, _height);
}

@end



每个对象分都有自己的成员变量, 而方法则是对象之间共享的。

红色箭头表示方法和对象   或方法和类名之间的调用关系

黑色箭头表示方法对成员变量的访问

输出结果如下图


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值