在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
- (id) init // 初始化对象 { if (self = [super init]) { // 初始化内容 } return self; } 存取方法
#import <Foundation/Foundation.h> /* * car3: 添加新的汽车引擎V8 和 轮胎WeatherRadial * */ @interface Engine : NSObject @end @implementation Engine - (NSString *) description { return (@"I am a Engine"); } @end @interface Tire : NSObject @end @implementation Tire - (NSString *) description { return(@"I am a Tire"); } @end #pragma mark *** Car *** @interface Car : NSObject { Engine *engine; Tire *tires[4]; } // 添加getter,setter - (Engine *) engine; - (void) setEngine:(Engine *) m_engine; - (Tire *) tireAtIndex: (int) index; //通过索引器访问该属性 - (void) setTire: (Tire *) m_tire : (int) index; - (void) print; @end @implementation Car //- (id) init // 初始化Car //{ // 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 *)m_engine { engine = m_engine; } - (Tire *) tireAtIndex:(int)index { if (index < 0 || index > 3) { NSLog(@"bad index (%d) in \"tireAtIndex:\"", index); exit(1); } return tires[index]; } - (void) setTire:(Tire *)m_tire :(int)index { if (index < 0 || index >3) { NSLog(@"bad index (%d) in \"setTire:atIndex\"", index); exit(1); } tires[index] = m_tire; } - (void) print { NSLog(@"%@",engine); NSLog(@"%@",tires[0]); NSLog(@"%@",tires[1]); NSLog(@"%@",tires[2]); NSLog(@"%@",tires[3]); } // 如果没有重写description方法,则 %@ 将输出对象的内存地址。 // 如: <Car: 0x10010c480> - (NSString *) description { return @"I am a Car!"; } @end // ******************* // V8 Engine Class @interface V8 : Engine @end @implementation V8 - (NSString *) description { return @"I am a V8 Engine!"; } @end // V8 // ******************* // WeatherRadial Tire @interface WeatherRadial : Tire @end @implementation WeatherRadial - (NSString *) description { return (@"I am a WeatherRadial Tire!!"); } @end int main (int argc, const char * argv[]) { Car *car; car = [Car new]; V8 *engine = [V8 new]; [car setEngine: engine]; int i; for (i = 0; i < 4; i++) { WeatherRadial *tire = [WeatherRadial new]; [car setTire:tire :i]; } [car print]; return 0 ; }
|
请发表评论