码迷,mamicode.com
首页 > 其他好文 > 详细

复合(Objective-C)

时间:2014-09-24 23:17:57      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   color   io   ar   for   div   

//实现CarParts
//实现CarParts
#import<Foundation/Foundation.h>


@interface Tire : NSObject
@end


@implementation Tire
-(NSString *)description
{
    return (@"I am a tire.I last a while.");
}
@end


@interface Engine : NSObject
@end


@implementation Engine
-(NSString *)description
{
    return(@"I am an engine.Vrooom!");
}
@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
-(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]);
}
@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;
}
结果:
bubuko.com,布布扣

复合(Objective-C)

标签:des   style   blog   http   color   io   ar   for   div   

原文地址:http://www.cnblogs.com/Xylophone/p/3991471.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!