Student.h- /*
- 设计一个学生类,
- 属性有:姓名,年龄,性别,成绩;
- 用setter设置器和getter访问器,进行赋值和取值;
- 顺便写出,set方法和get方法的命名规范;
-
- */
- #import <Foundation/Foundation.h>
- typedef enum {
- kSexMan,
- kSexWoman,
- kSexYao
- }Sex;
- @interface Student : NSObject
- //姓名,年龄,性别,成绩
- {
- NSString *_name;
- int _age;
- Sex _sex;
- }
- //用setter设置器和getter访问器,进行赋值和取值;
- //setter设置器
- -(void)setName:(NSString *)name;
- -(void)setAge:(int)age;
- -(void)setSex:(Sex)sex;
- //getter访问器
- -(NSString*)name;
- -(int)age;
- -(Sex)sex;
- @end
复制代码
Student.m
- #import "Student.h"
- @implementation Student
- -(void)setName:(NSString *)name{
-
- _name=name;
- }
- -(void)setAge:(int)age{
- _age=age;
- }
- -(void)setSex:(Sex)sex{
- _sex=sex;
- }
- //getter访问器
- -(NSString*)name{
- return _name;
- }
- -(int)age{
- return _age;
- }
- -(Sex)sex{
- return _sex;
- }
- @end
复制代码
main.m- #import <Foundation/Foundation.h>
- #import "Student.h"
- int main(int argc, const char * argv[]) {
- @autoreleasepool {
- Student *stu=[Student new];
-
- [stu setName:@"XiaoMing"];
- [stu setAge:18];
- [stu setSex:kSexYao];
- //姓名,年龄,性别,成绩
- NSLog(@"姓名:%@,年龄:%d,性别:%u ",[stu name],[stu age],[stu sex]);
- }
- return 0;
- }
复制代码 |