天天看点

OC语言--成员变量作用域

一、成员变量作用域

成员变量有四种作用域:

@public : 在任何地方都能直接访问成员变量;

@private : 只能在当前类的对象方法中直接访问(如果成员变量未声明直接实现,则@implementation中默认是@private)

@protected : 可以在当前类及其子类的对象方法中直接访问(成员变量的声明@interface中默认为@protec);

@package : 只要处在同一个框架中,就能直接访问对象的成员变量。

代码示例:

//父类-Person :声明不同作用域的成员变量,声明@private、@protectd成员变量的set、get方法
/********************Person类的声明***********************************/
@interface Person : NSObject
{
    int _age;    //@interface中声明的默认为@protected;
    
    @public
    int _no;    //可以在任何地方直接访问对象的成员变量
    
    @private
    int _weight;    //只能在当前类的对象方法中直接访问
    int _money;        //_weight、_money都是@private
    
    @protected        
    int _height;    //能在当前类和子类的对象方法中直接访问
}

- (void)setWeight:(int)weight;
- (int)weight;

- (void)setHeight:(int)height;
- (int)height;
@end

/**************Person类的实现************************************/
//在实现中定义成员变量
@implementation Person
{
    char * _phone;    //在@implementation中可以定义@interface中没有声明的成员变量;默认为@private
    
    @public
    char * _address;    //@public
    //int _age;            //在@interface已经有_age成员变量,所以此处不能再定义同名的成员变量;
}
- (void)setWeight:(int)weight
{
    _weight = weight;
}
- (int)weight
{
    return weight;
}

- (void)setHeight:(int)height
{
    _height = height;
}
- (int)height
{
    return _height;
}
@end

//子类-Student
/***************************Person子类-Student类的声明***********************/
@interface Student :Person
- (void)test;
@end

/******************************Student类的实现******************************/
@implementation Student
- (void)test
{
    _age = 20;    //父类Person中的_age默认为@protected,所以访问变量可以被Person类和其子类(Student)直接访问
    
    _no = 20;    //父类中的_no为@public,所以该变量可以在任何地方访问
    
    //_weight = 30;        //父类_weight为@private,所以该变量只能被当前类Person直接访问,Student不能直接访问
    //_money = 40;
    [self setWeight:30];     //如果想赋值只能通过set方法访问成员变量
    
    _height = 178;        //_height为@protect,跟_age使用方法一样,可以在当前类和子类中直接访问
}
@end

/**************************Person类的应用*************************************/
int main()
{
    Person *p = [Person new];
    //p->_age = 40;        //@protected只能在Person类和Student类中直接访问,所以此处不能直接访问
    p->_no = 20;        //@public的成员变量可以在任何位置直接访问
    //p->_weight = 50;    //@private的成员变量只能在Person类中直接访问,此处不可用
    //p->_height = 180;    //@protected只能在Person类和Student类中直接访问,所以此处不能直接访问
    
    [p setWeight:50];    //如果要赋值可以采用set方法
    p.height = 180;        //点运算,调用set方法
}
           

总结:

1.掌握成员变量作用域

@public : 在任何地方都能直接访问成员变量;

@private : 只能在当前类的对象方法中直接访问(如果成员变量未声明直接实现,则@implementation中默认是@private)

@protected : 可以在当前类及其子类的对象方法中直接访问(成员变量的声明@interface中默认为@protec);

@package : 只要处在同一个框架中,就能直接访问对象的成员变量。

2.成员变量在类中可以没有声明,只有实现,这样系统不会爆错,但是会有警告,但是不建议用,

    解释:@interface中没有成员变量的声明,直接在@implementation中定义成员变量,但是不建议用。

[email protected]与@end之间的成员变量默认的作用域为@protected;@implementation与@end中的成员变量作用域默认为@private

4.名词:超类。

   超类就是父类,superclass。

   子类,subclass。