zoukankan      html  css  js  c++  java
  • oc 01 类、异常处理

    类的语法

    Fraction.h 类声明

    #import <Foundation/Foundation.h>
    #ifndef Fraction_h
    #define Fraction_h
    
    static int t = 0 ; // 类变量
    @interface Fraction:NSObject{
        int numerator;
    @public int denominator;
    }
    -(void)setNumerator:(int)numerator;
    -(void)setDenominator:(int)denominator;
    -(void)setNumerator:(int)numerator andDenominator:(int)denominator;
    
    -(int)numerator;
    -(int)denominator;
    -(void)print; // 成员方法
    +(void)t;       // 类方法
    
    @end
    
    #endif /* Fraction_h */
    

    Fraction.m 类定义

    #import "Fraction.h"
    #import "ZeroException.h"
    
    @implementation Fraction
    
    -(void)setNumerator:(int)n{
        numerator = n;
    }
    -(void)setDenominator:(int)d{
        if(d==0){
            NSException *e = [ZeroException exceptionWithName:@"ZeroException" reason:@"denominator cant be 0!" userInfo:nil];
            @throw e; // 抛出异常
        }
        denominator = d;
    }
    -(void)setNumerator:(int)n andDenominator:(int)d{
        if(d==0){
            NSException *e = [ZeroException exceptionWithName:@"ZeroException" reason:@"denominator cant be 0!" userInfo:nil];
            @throw e;
        }
        numerator  = n;
        denominator = d;
    }
    -(int)numerator{
        return numerator;
    }
    -(int)denominator{
        return denominator;
    }
    -(void)print{
        printf("%d/%d
    ",numerator,denominator);
    }
    +(void)t{
        printf("+t:thie class variable t is %d
    ",++t);
    }
    -(NSString*)description{  // toString
        return @"I am a fraction";
    }
    
    @end
    
    

    ZeroException.h 异常声明

    #import <Foundation/Foundation.h>
    
    @interface ZeroException:NSException
    @end
    
    

    ZeroException.m 异常定义

    
    #import <Foundation/Foundation.h>
    #import "ZeroException.h"
    
    @implementation ZeroException
    
    @end
    

    main.c

    #import <Foundation/Foundation.h>
    #import "Fraction.h"
    #import "ZeroException.h"
    
    int main(int argc , const char* argv[])
    {
        Fraction *frac = [[Fraction alloc]init];
        [frac setNumerator:3 andDenominator:4];
        [frac print];
        [Fraction t];
        NSLog(@"%@",frac); // description方法
        
        @try{
            [frac setDenominator:0];
        }@catch(ZeroException *ze){ // 捕获异常
            printf("%s
    ",[[ze reason] cString]);
        }@finally{
            printf("finally run");
        }
        return 0 ;
    }
    
  • 相关阅读:
    转载Dockerfile 中 RUN, CMD, ENTRYPOINT 的区别
    在linux上通过ssh使用github
    dns服务
    centos6 free 和 centos 7的free 的差异与对比
    无重复字符的最长子串
    go get命令在go mod目录下与正常目录执行的区别
    安装git
    转载 筛子算法之golang实现求素数解析
    Go语言基础之并发
    go之无缓冲channel(通道)和有缓冲channel(通道)
  • 原文地址:https://www.cnblogs.com/hiqianqian/p/7015551.html
Copyright © 2011-2022 走看看