成員變量的作用域

@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萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章