您的位置:首页 > 其它

oc学习笔记-set和get函数 基础(Foundation)面向对象之封装方法

2015-04-19 02:03 381 查看
#import <Foundation/Foundation.h>
/************************************
*oc get(readonly只读) set(只写)函数 练习
*set方法 提供一个方法给外界设置成员变量值  可以在方法里面对参数就行过滤
*命名规范:1>方法名必须以set开头 2>set后面跟上成员变量名称 其名称首字母必然大写3>返回值一定是void  4>一定要接受一个参数
*get 方法作用返回对象内部成员变量 参数类型跟成员变量类型一致 5>形参的名称不能跟成员变量名一致。
命名规范:返回值类型与成员变量类型一致  方法名跟成员变量量一致  不需要接受任何参数
*cc 07-set方法.m  -framework Foundation
************************************/
@interface students : NSObject
{
int age;
}
- (void)setAge : (int)newAge;
- (int)age;
- (void)print;
@end
@implementation students
//set方法
- (void)setAge : (int)newAge
{
if(newAge<=1)
{
age = 1;
}
}
//get 方法
- (int)age
{
return age;
}
- (void)print
{
NSLog(@"%d",age);
}
@end

int main()
{
students *stu  = [ students new ];
[stu setAge : -10];
[stu print];
NSLog(@"学生年龄是%d",[stu age]);
return 0;
}


封装

#import <Foundation/Foundation.h>
/*
*oc封装 好处:1>过滤不合理的值 2>屏蔽内部赋值过程3>让外界不必关注内部细节
*外部访问内部成员变量(_标记)练习
*/
typedef  enum
{
sexMan,
sexWomen
} Sex;

@interface results : NSObject
{
int _cScore;//c语言得分
int _ocScore;//oc得分
Sex _sex;//性别
}
- (void)setCscore : (int)cScore;
- (int)cScore;

- (void)setOCscore : (int)OcScore;
- (int)OcScore;

- (void)setSex : (Sex)sex;
- (Sex)sex;

- (int)total;
- (int)average;
@end

@implementation results
- (void)setCscore : (int)cScore
{
_cScore = cScore;
}
- (int)cScore
{
return _cScore;
}

- (void)setOCscore : (int)OcScore
{
_ocScore = OcScore;
}
- (int)OcScore
{
return _ocScore;
}

- (void)setSex : (Sex)sex
{
_sex = sex;
}
- (Sex)sex
{
return _sex;
}

- (int)total
{
return  _cScore + _ocScore;
}
- (int)average
{
return (_cScore +  _ocScore )/2;
}
@end
int  main()
{
results *s = [results new];
[s setCscore : 80];
[s setOCscore : 100];
[s setSex : sexWomen];//写入一个性别
NSLog(@"%d\t%d\t%d",[s total],[s average],[s sex]);//get方法读取set写入数据
return 0;
}


面向对象的方式是对象的方法调用

下面是类的方法调用

#import <Foundation/Foundation.h>

@interface person : NSObject

+ (void)personClassName;
@end

@implementation person

+ (void)personClassName
{
NSLog(@"person类,类方法调用");
}

@end

int main()
{
[person personClassName];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: