CarParts2

来源:互联网 发布:你还知哪些有趣的鱼类 编辑:程序博客网 时间:2024/06/05 20:23

修改上文的代码如下:

////  main.m//  CarParts////  Created by cloud on 13-3-8.//  Copyright (c) 2013年 cloud. All rights reserved.//#import <Foundation/Foundation.h>@interface Tire:NSObject@end@implementation Tire- (NSString *) description{    return (@"I am a tire.I last a while");}//description@end@interface Engine : NSObject@end@implementation Engine- (NSString *)description{    return (@"I am an engine.Vroom!");}@end@interface Car : NSObject{    Engine *engine;    Tire   *tires[4];}- (Engine *) engine;- (void) SetEngine: (Engine *) newEngine;- (Tire *) tireAtIndex: (int) index;- (void) setTire:(Tire *) tire atIndex:(int) index;- (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);//}- (Engine *) engine{    return (engine);}- (void) SetEngine:(Engine *)newEngine{    engine=newEngine;}- (void) setTire:(Tire *)tire atIndex:(int)index{    if (index<0||index>3) {        NSLog(@"bad index (%d) in setTire:atIndex;",index);        exit(1);    }        tires[index] = tire;}-(Tire *)tireAtIndex:(int)index{    if(index<0 || index >3)    {        NSLog(@"bad index (%d) in tireAtIndex;",index);        exit(1);    }    return (tires[index]);}- (void) print{    NSLog(@"%@",engine);        NSLog(@"%@",tires[0]);    NSLog(@"%@",tires[1]);    NSLog(@"%@",tires[2]);    NSLog(@"%@",tires[3]);}@endint main(int argc, const char * argv[]){    @autoreleasepool {                // insert code here...        Car *car;        car=[Car new];        Engine *engine=[Engine new];        [car SetEngine:engine];                int i;        for(i=0;i<4;i++)        {            Tire *tire=[Tire new];            [car setTire:tire                 atIndex:i];                    }                        [car print];            }    return 0;}


运行结果如下:

注意:

- (void) setTire:(Tire *)tire atIndex:(int)index,Objective-c中多参数方法的使用和C中很不一样。这个相当于c中void setTireatIndex(Tire * tire,int index)。它是把方法名拆分为和参数个数相同,中间用空格隔开。