封装set方法
@interface Student : NSObject
{
int age;
int no;
}
- (void)setAge:(int)newAge;
- (int)age;
- (void)study;
@end
@implementation Student
- (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 setAge:10];
NSLog(@"学生的年龄是%d岁", [stu age]);
return 0;
}
封装get方法
typedef enum {
SexMan,
SexWoman
} Sex;
@interface Student : NSObject
{
int _no;
Sex _sex;
}
- (void)setSex:(Sex)sex;
- (Sex)sex;
- (void)setNo:(int)no;
- (int)no;
@end
@implementation Student
- (void)setSex:(Sex)sex
{
_sex = sex;
}
- (Sex)sex
{
return _sex;
}
- (void)setNo:(int)no
{
_no = no;
}
- (int)no
{
return _no;
}
@end
int main()
{
Student *stu = [Student new];
[stu setSex:SexMan];
[stu setNo:10];
[stu sex];
[stu no];
return 0;
}
封装的练习
#import <Foundation/Foundation.h>
@interface Score : NSObject
{
int _cScore;
int _ocScore;
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;
}