Objective-C 类的复合

//
//  main.m
//  Study
//
//  Created by DwightDing on 16/3/12.
//  Copyright © 2016年 DwightDing. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface Tire : NSObject
@end//Tire

@implementation Tire

-(NSString *)description{
    return (@"I'm a Tire, I last a while");
}//description在Cocoa中定义

@end

@interface Engine : NSObject
@end
@implementation Engine

-(NSString *)description
{
    return (@"I am an engine.Vroom");
}

@end

@interface Car : NSObject
{
    Engine *engine;
    Tire *tires[4];
}
-(void)print;
@end
@implementation Car

-(id) init
{
    if(self = [super init]){
        engine = [Engine new];
        tires[0] = [Tire new];
        tires[1] = [Tire new];
        tires[2] = [Tire new];
        tires[3] = [Tire new];
    }
    return self;
}
-(void)print
{
    NSLog(@"%@",engine);
    NSLog(@"%@",tires[0]);
    NSLog(@"%@",tires[1]);
    NSLog(@"%@",tires[2]);
    NSLog(@"%@",tires[3]);
}
@end

int main(int argc, const char * argv[]) {
    Car *car;
    car = [Car new];
    [car print];
    return 0;
}

对类进行扩展:

//
//  main.m
//  Study
//
//  Created by DwightDing on 16/3/12.
//  Copyright © 2016年 DwightDing. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface Tire : NSObject
@end//Tire

@implementation Tire
-(NSString *)description{
    return (@"I'm a Tire, I last a while");
}//description在Cocoa中定义
@end

//Define Engine
@interface Engine : NSObject
@end

//setter getter
@implementation Engine
-(NSString *)description
{
    return (@"I am an engine.Vroom");
}
@end

//define Car
@interface Car : NSObject
{
    Engine *engine;
    Tire *tires[4];
}
-(void)setTire : (Tire *)tire atIndex : (int) index;
-(Tire *)tireAtIndex : (int) index;
-(Engine *) engine;
-(void) setEngine : (Engine *) newEngine;
-(void)print;
@end
@implementation Car
//realize function
-(void)setTire : (Tire *)tire atIndex : (int) index
{
    if (index<0||index>3) {
        NSLog(@"error");
        exit(1);
    }
    tires[index]=tire;
}

-(Tire *)tireAtIndex : (int) index
{
    if (index<0||index>3) {
        NSLog(@"error");
        exit(1);
    }
    return (tires[index]);
}
-(void) setEngine : (Engine *) newEngine
{
    engine=newEngine;
}
-(Engine *) engine
{
    return (engine);
}

-(void)print
{
    NSLog(@"%@",engine);
    NSLog(@"%@",tires[0]);
    NSLog(@"%@",tires[1]);
    NSLog(@"%@",tires[2]);
    NSLog(@"%@",tires[3]);
}
@end

int main(int argc, const char * argv[]) {
    Car *car = [Car new];
    Engine *engine=[Engine new];
    [car setEngine:engine];
    for (int i = 0; i < 4; i++) {
        Tire *tire = [Tire new];
        [car setTire:tire atIndex:i];
    }
    [car print];
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值