iOS学习开发

自定义类

2017-06-28  本文已影响0人  开发者zhang
  1. BNRPerson.h

    #import <Foundation/Foundation.h>
    
    @interface BNRPerson : NSObject
    
    //使用属性(properties),则可省略存取方法。
    //@property (nonatomic) float heightInMeters;
    //@property (nonatomic) int weightInKilos;
    
    {
        //BNRPerson类拥有两个实例变量
        float _heightInMeters;
        int _weightInKilos; 
    }
    
    //BNRPerson类拥有可以读取并设置实例变量的方法
    -(float)heightInMeters;
    -(void)setHeightInMeters:(float)h;
    -(int)weightInKilos;
    -(void)setWeightInKilos:(int)w;
    
    //BNRPerson类拥有计算Body Mass Index的方法
    -(float)bodyMassIndex;
    @end
    
  2. BNRPerson.m

    #import "BNRPerson.h"
    
    @implementation BNRPerson
    //声明的方法加入实现代码
    -(float)heightInMeters
    {
        return _heightInMeters;
    }
    
    -(void)setHeightInMeters:(float)h
    {
        _heightInMeters = h;
    }
    
    -(int)weightInKilos
    {
        return _weightInKilos;
    }
    
    -(void)setWeightInKilos:(int)w
    {
        _weightInKilos = w;
    }
    
    -(float)bodyMassIndex
    {
        return _weightInKilos/(_heightInMeters * _heightInMeters);
    }
    
    @end
    
  3. main.m

   #import <Foundation/Foundation.h>
   #import "BNRPerson.h"
   
   int main(int argc, const char * argv[]) {
       @autoreleasepool {
           // insert code here...
           NSLog(@"Hello, World!");
           BNRPerson *korwin = [[BNRPerson alloc]init];
           
           [korwin setWeightInKilos:96];
           [korwin setHeightInMeters:1.8];
           
           float hei = [korwin heightInMeters];
           int wei = [korwin weightInKilos];
           NSLog(@"%.2f  %d\n",hei,wei);
           
           float bmi = [korwin bodyMassIndex];
           NSLog(@"%f\n",bmi);
       }
       return 0;
   }
   ```
上一篇 下一篇

猜你喜欢

热点阅读