oc——类——声明 定义 实现

声明

类的声明,又称类的前向声明,即forward declaration,告诉编译器class类型,但当前并不知道class具体细节,是不完全类型
  • 类的声明只能用于指针类型,因为指针类型字长固定,编译器知道分配多少内存空间,如何操作指针类型
  • 类的声明不能用于对象(instance object&class object),因为对于instance object,编译器需要知道class object内容,对于class object,编译器需要知道meta-class object内容
@class FBAnimal;

void incomplete_class()
{
    FBAnimal *animal;
    //animal = [[FBAnimal alloc] init];
}

定义

@interface FBAnimal : NSObject
{
@public
    int _rice;
    int _meat;
}

- (void)feedRice:(int)rice;
- (void)feedRice:(int)rice andMeat:(int)meat;

+ (void)setMain:(int)main;
+ (void)setMain:(int)main andSub:(int)sub;

@end
注:类所有方法都是运行期bind,因此类必须提供实现,否则link error,因为编译器编译期无法确定方法成员(instance method和class method)是否被访问

实现

@implementation FBAnimal

- (void)feedRice:(int)rice
{
    NSLog(@"feedRice:");
}

- (void)feedRice:(int)rice andMeat:(int)meat
{
    NSLog(@"feedRice:andMeat:");
}

+ (void)setMain:(int)main
{
    NSLog(@"setMain:");
}

+ (void)setMain:(int)main andSub:(int)sub
{
    NSLog(@"setMain:andSub");
}

@end
注:类所有方法都是运行期bind,编译器编译期无法确定方法成员(instance method和class method)是否被访问,为避免运行期crash,类所有方法必须提供实现,否则编译warning

总结

  • @class classname——类的声明,@interface classname——类的定义,@implement classname——类的实现
  • 类的定义和实现编译成为class object&meta-class object内容:数据成员定义编译成为class object内容,instance method实现编译成为class object内容,class method实现编译成为meta-class object内容

self&成员访问

self类似于c++的this,表示当前instance object,instance object访问数据成员和instance method,class object访问class method,因此:
  • self只能出现在instance method中,只能访问数据成员和instance method,不能访问class method,instance method中存在instance object,无class object
  • self不能出现在class method中,class method中只能访问class method,不能访问数据成员和instance method,class method中存在class object,无instance object
- (void)use_animal
{
    FBAnimal *animal = [[FBAnimal alloc] init];
    
    animal->_rice = 5;
    animal->_meat = 8;
    
    [animal feedRice:15];
    [animal feedRice:15 andMeat:18];
    
    [FBAnimal setMain:25];
    [FBAnimal setMain:25 andSub:28];
}
output:
feedRice:
feedRice:andMeat:
setMain:
setMain:andSub
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值