OC语言—— @public和 @private 及 @protected

一,概念

  在C语言中,我们学习的局部变量,它们有自己的作用域。那OC中的成员变量也有它的的作用域。

二,主要分为下面三种情况

  @public:任何地方都可以直接访问

  @private:只能在当前类的对象方法中直接访问

  @protected:可以在父以及子类的对象方法中直接访问

三,小练习

#import <Foundation/Foundation.h>

@interface Person : NSObject
{
    int _no;
    
@public // 在任何地方都能直接访问对象的成员变量
    int _age;
    
@private  // 只能在当前类的对象方法中直接访问
    int _height;
    
@protected // 能在当前类和子类的对象方法中直接访问
    int _weight;
    int _money;
}

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

- (void)test;
@end

@implementation Person
{
    int _aaa;// 默认就是私有
    
@public
    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

@interface Student : Person
- (void)study;
@end

@implementation Student
- (void)study
{
    // _height = 10;
    [self setHeight:10];
    
    int h = [self height];
    
    _weight = 100;
}
@end

@implementation Car : NSObject
{
@public
    int _speed;
    
@protected
    int _wheels;
}

- (void)setSpeed:(int)speed
{
    _speed = speed;
}
- (int)speed
{
    return _speed;
}

@end

int main()
{
        Student *stu = [Student new];
    
        [stu setHeight:100];
    
        NSLog(@"%d", [stu height]);
        
        /*
         Car *c = [Car new];
         c->_speed = 250;
         */
        //c.speed = 10;
        
        // NSLog(@"%d", c.speed);
        
        //[c setSpeed:<#(int)#>];
        
        /*
         Person *p = [Person new];
         p->_bbb = 10;
         p->_age = 100;
         */
        //p->_height = 20;
    
        //p->_weight = 10;
 
    return 0;
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值