A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

题目要求:

             定义一个Person的类,并包含姓名,年龄,身高,体重,性别,设定并打印出年龄的值.



一.传统setter方法和getter方法
  1. //注:为使使代码在一块清晰可见,我将.h和.m中的代码都放在main.m文件中

  2. #import <Foundation/Foundation.h>

  3. //声明实例变量
  4. @interface Person : NSObject
  5. {
  6.     NSString *_name;
  7.     int _age;
  8.     float _height;
  9.     float _weight;
  10.     int _sex;
  11. }

  12. //set方法和get方法的声明
  13. -(void)setName:(NSString *) name;
  14. -(NSString *)name;

  15. -(void)setAge:(int)age;
  16. -(int)age;

  17. -(void)setHeight:(float)height;
  18. -(float)height;

  19. -(void)setWeight:(float)weight;
  20. -(float)weight;

  21. -(void)setSex:(int)sex;
  22. -(int)sex;

  23. @end



  24. #import "Person.h"

  25. //set方法和get方法的实现
  26. @implementation Person
  27. -(void)setName:(NSString *) name{
  28.    
  29.     _name = name;
  30.    
  31. }
  32. -(NSString *)name{
  33.    
  34.    
  35.     return _name;
  36. }

  37. -(void)setAge:(int)age{
  38.    
  39.     _age = age;
  40.    
  41. }
  42. -(int)age{
  43.    
  44.     return _age;
  45.    
  46. }

  47. -(void)setHeight:(float)height{
  48.    
  49.    
  50.     _height = height;
  51. }
  52. -(float)height{
  53.    
  54.     return _height;
  55. }

  56. -(void)setWeight:(float)weight{
  57.    
  58.     _weight= weight;
  59.    
  60. }
  61. -(float)weight{
  62.    
  63.     return _weight;
  64.    
  65. }

  66. -(void)setSex:(int)sex{
  67.    
  68.     _sex = sex;
  69.    
  70. }
  71. -(int)sex{
  72.    
  73.    
  74.     return _sex;
  75. }

  76. @end




  77. #import <Foundation/Foundation.h>
  78. #import "Person.h"
  79. int main(int argc, const char * argv[]) {
  80.     @autoreleasepool {
  81.         
  82.         Person *p = [Person new];
  83.         
  84.         //为实例变量赋值并打印
  85.         [p setAge:18];
  86.         NSLog(@"age = %d",[p age]);
  87.         
  88.     }
  89.     return 0;
  90. }
复制代码




二.@property 增强型的使用
  1. //注:为使使代码在一块清晰可见,我将.h和.m中的代码都放在main.m文件中

  2. #import <Foundation/Foundation.h>


  3. @interface Person : NSObject

  4. //通过@property增强型来实现set方法和get方法的声明和实现
  5. @property NSString* name;

  6. @property int age,sex;

  7. @property float height,weight;

  8. @end


  9. #import "Person.h"

  10. @implementation Person
  11. @end



  12. #import <Foundation/Foundation.h>
  13. #import "Person.h"
  14. int main(int argc, const char * argv[]) {
  15.     @autoreleasepool {
  16.         
  17.         Person *p = [Person new];
  18.         
  19.         //通过点语法为实例变量赋值并打印
  20.         p.age = 18;
  21.         NSLog(@"age = %d",p.age);
  22.         
  23.     }
  24.     return 0;
  25. }
复制代码






1 个回复

倒序浏览
收藏了!                                    
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马