main.m
================================================================
#import <Foundation/Foundation.h>
#import "Engine.h"
#import "Tire.h"
#import "Car.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
/*
复合:
在OC中就是一个类的成员变量是由其他的一些类组成,即一个类包含了好几个其他类
*/
Engine *engine=[Engine new];
//NSLog(@"%@",engine);//通过NSLog输出一个对象是,对象会自动去调用它的description的方法,输出它各自的描述
Tire *tire=[Tire new];
//NSLog(@"%@",tire);
Car *car=[Car new];
car->_engine=engine;
// for (int i=0; i<4; i++)
// {
// Tire *tire=[Tire new];
// car->_tires[i]=tire;
// }
// [car run];
Car *car_1=[Car new];
[car_1 setEngine:engine];
for (int i=0; i<4; i++)
{
Tire *tire1=[Tire new];
[car_1 setTire:tire1 atIndex:i ];
}
/*
继承是在对象之间创建'is-a'关系,但是不是任何清华下都适合使用的复合,则是在对象之间建立了一个'has a'(有一个)的关系,如果能‘X 有 Y’,既可以使用复合
复合使用在将一些个体祝贺起来形成一个新的整体的情况下。
*/
//@class_P85
}
return 0;
}
#import <Foundation/Foundation.h>
#import "Tire.h"
#import "Engine.h"
@interface Car : NSObject
{
@public
Engine *_engine;//引擎
Tire *_tires[4];//四个轮子(指针数组,数组中每一个元素存储的都是一个地址,都是指向Tire,即每个元素都是Tire的一个实例对象)
}
-(void)run;
-(void)setEngine:(Engine *)engine;
-(Engine *)engine;
-(void)setTire:(Tire *)tirs;
-(Tire *)tire;
-(void)setTire:(Tire *)tire atIndex:(NSUInteger)index;
@end
#import "Car.h"
@implementation Car
-(void)run
{
NSLog(@"%@",_engine);
for (int i=0; i<4; i++)
{
NSLog(@"%@",_tires[i]);
//NSLog(@"%@",[self tireAtIndex:i]);
}
}
-(void)setEngine:(Engine *)engine
{
_engine=engine;
}
-(Engine *)engine
{
return _engine;
}
//根据index来作正确性校验
-(void)setTire:(Tire *)tire atIndex:(NSUInteger)index
{
if(index<0 || index>3)
{
NSLog(@"设置轮胎位置不正确");
}
else
{
_tires[index]=tire;
}
}
-(Tire *)tireAtIndex:(int)index
{
if (index<0|| index>3)
{
NSLog(@"获取轮胎位置不正确");
return nil;
}
else
{
return _tires[index];
}
}
@end
#import <Foundation/Foundation.h>
@interface Engine : NSObject
@end
#import "Engine.h"
@implementation Engine
//重写description方法,者里只是重写description的属性的访问器,并不是重写description这个类方法
-(NSString *)description
{
return @"我是一个引擎,我在努力工作!";
}
@end
Tire.h
#import <Foundation/Foundation.h>
@interface Tire : NSObject
@end
============================================================
Tire.m
#import "Tire.h"
@implementation Tire
-(NSString *)description
{
return @"我是一个轮胎,我诚恳的托起了整个车身";
}
@end