成员变量的作用域

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

 @private : 只能在当前类的对象方法中直接访问(@implementation中默认是@private)
 @protected : 可以在当前类及其子类的对象方法中直接访问  (@interface中默认就是@protected)
 @package : 只要处在同一个框架中,就能直接访问对象的成员变量
 

 @interface和@implementation中不能声明同名的成员变量


person.h

@interface Person : NSObject

{
    int  _no; // 默认的是protected
	  
    @public // 在任何地方都能直接访问对象的成员变量
    int  _age;

    @private
    int  _height;

    // 只能在 当前类 的对象方法中直接访问,只能在person类中访问,person类的对象中不可以
    // 子类中含有这个变量,只是不能直接访问,需要用setter
    @protected // 能在当前类和子类的对象方法中直接访问
    int  _weight;
    int  _money;
}

- (void)setHeight:(int)height;
- (int)height;
- (void)test;

@end


person.m

#import "Person.h"

@implementation Person
{
    // 实现里也可以有成员变量
    int  _aaa;// 默认就是私有

    @public // 就算加上@public也是无用的,因为main函数中,只import .h文件 仍然是私有的
    int  _bbb;

    // @implementation中不能定义和@interface中同名的成员变量
    // int  _no;

}

- (void)test
{
    _age = 19;
    _height = 20;
    _weight = 50;
    _aaa = 10;
}

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

- (int)height
{
    return _height;
}

@end

main函数

int main(int argc, const char * argv[])
{
    @autoreleasepool {


        Student *stu = [Student new];


        [stu setHeight:100];


        NSLog(@"%d", [stu height]);


        Person *p = [Person new];


        p->_bbb = 10;


        p->_age = 100;
    }


    return 0;
}

发布了59 篇原创文章 · 获赞 5 · 访问量 2万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章