一 概述
局部变量,全局变量都有自己的作用域,成员变量也不例外,成员变量有一下四种类型
- @private:只能在当前类的实现@implementation中直接访问
- @protected:可以在当前类以及子类的实现@implementation中直接访问
- @public:任何地方都可以直接访问
- @package:同一个“体系内(框架)"可以访问,介于@private和@public之间
二 作用域演示
2.1 类间关系
- Person类继承自NSObject
- Student继承自Person
2.2 Person.h头文件中变量声明
#import <Foundation/Foundation.h>
@interface Person : NSObject
{
int _no;
@public
int _age;
@private
int _height;
@protected
int _weight;
@package
double _money;
}
-(void)setHeight:(int)height;
-(int)height;
@end
- 默认类型的变量
_no
- public类型的变量
_age
- private类型的
_height
- protected类型的
_weight
- package类型的
_money
2.3 Person.m实现类中
#import "Person.h"
@implementation Person
-(void)setHeight:(int)height
{
_height=height;
}
-(int)height
{
return _height;
}
@end
2.4 Student.h头文件
#import "Person.h"
@interface Student : Person
-(void)study;
@end
2.5 Student.m实现
#import "Student.h"
@implementation Student
-(void)study
{
_no=001; //没有定义,默认protected
_age=10; //public,都能访问
//_height=170;//private 只能在当前类访问
self.height=170;//private 通过点语法访问
_weight=60;
_money=100;
}
@end
2.6 main.m入口文件
Person *p=[Person new];
//p->no, p->_height,p->_weight //private
p->_money=100;//package属性可以访问
p->_age=10;//public属性可以访问
三 main.m同一个文件中类调用
#import <Foundation/Foundation.h>
#import "Person.h"
#import "Student.h"
@implementation Car:NSObject
{
@public
int _speed;
int _wheels;
}
-(void)setSpeed:(int)speed
{
_speed=speed;
}
-(int)speed
{
return _speed;
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
Person *p=[Person new];
//p->no, p->_height,p->_weight //private
p->_money=100;//package属性可以访问
p->_age=10;//public属性可以访问
Car *car=[Car new];
car->_speed=200;
}
return 0;
}