OC三大特性之封装

set方法

 1.作用: 提供一个方法给外界设置成员变量值,可以在方法里面对参数进行相应过滤
 2.命名规范:
 1> 方法名必须以set开头
 2> set后面跟上成员变量的名称,成员变量的首字母必须大写
 3> 返回值一定是void
 4> 一定要接收一个参数,而且参数类型跟成员变量类型一致
 5> 形参的名称不能跟成员变量名一样
 */
- (void)setAge:(int)newAge;

 get方法
 1.作用:返回对象内部的成员变量
 2.命名规范:
 1> 肯定有返回值,返回值类型肯定与成员变量类型一致
 2> 方法名跟成员变量名一样

 3> 不需要接收任何参数


#import <Foundation/Foundation.h>


@interface Student : NSObject
{
    // 成员变量尽量不要用@public
    // @public
    int age;
    
    //@public
    // 只读(readonly):只允许外界访问我的no,不允许外界修改我的no
    int no; // 只需要提供get方法
}
- (int)age;


- (void)study;


@end


@implementation Student


// set方法的实现
- (void)setAge:(int)newAge
{
    // 对传进来的参数进行过滤
    if (newAge <= 0)
    {
        newAge = 1;
    }
    
    age = newAge;
}


- (int)age
{
    return age;
}


- (void)study
{
    NSLog(@"%d岁的学生在学习", age);
}


@end


int main()
{
    Student *stu = [Student new];
    //stu->age = -10;
    
    //stu->age = 10;
    
    [stu setAge:10];
    
    
    NSLog(@"学生的年龄是%d岁", [stu age]);
    
    //[stu study];
    
    
    return 0;
}

练习:

 4.设计一个成绩类
 * C语言成绩(可读可写)
 * OC成绩(可读可写)
 * 总分(只读)
 * 平均分(只读)

#import <Foundation/Foundation.h>

@interface Score : NSObject
{
    int _cScore; // C语言成绩
    int _ocScore; // OC成绩
    
    int _totalScore;// 总分
    int _averageScoe; // 平均分
}

- (void)setCScore:(int)cScore;
- (int)cScore;

- (void)setOcScore:(int)ocScore;
- (int)ocScore;

- (int)totalScore;
- (int)averageScore;

@end

@implementation Score
- (void)setCScore:(int)cScore
{
    _cScore = cScore;
    
    // 计算总分
    _totalScore = _cScore + _ocScore;
    _averageScoe = _totalScore/2;
}
- (int)cScore
{
    return _cScore;
}

- (void)setOcScore:(int)ocScore
{
    _ocScore = ocScore;
    
    // 计算总分
    _totalScore = _cScore + _ocScore;
    _averageScoe = _totalScore/2;
}
// 监听成员变量的改变

- (int)ocScore
{
    return _ocScore;
}

- (int)totalScore
{
    return _totalScore;
}
- (int)averageScore
{
    return _averageScoe;
}
@end


int main()
{
    Score *s = [Score new];
    
    [s setCScore:90];
    [s setOcScore:100];
    
    [s setCScore:80];
    
    
    int a = [s totalScore];
    
    NSLog(@"总分:%d", a);
    
    return 0;
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值