OC基础——复合

这段代码展示了Objective-C中如何定义和初始化一个Car类,该类包含Engine和Tire对象。在main函数中创建了一个Car实例并打印了其发动机和轮胎的信息。这是一个简单的面向对象编程示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//
//  main.m
//  yhj
//
//  Created by yinhaijing on 2022/7/20.
//

#import <Foundation/Foundation.h>

#pragma  mark -复合
@interface Engine : NSObject
@end
@implementation Engine
- (NSString *) description
{
    return (@"i am an engine");
}//description
@end//Engine

@interface Tire :NSObject
@end
@implementation Tire
-(NSString *) description
{
    return (@"i am a tire.i last a while.");
}//description
@end//Tire

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

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

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

#pragma mark - 间接
/*int main(int argc, const char * argv[]) {
    /*if(argc==1){
        NSLog(@"you need input file!");
        return 1;
    }/*
    FILE *fp=fopen(argv[1],"r");
    
    //FILE *fp=fopen("/tmp/test.txt","r");
    FILE *fp=fopen("/usr/share/dict/words","r");
    char word[100];
    while(fgets(word,100,fp))
    {
        word[strlen(word)-1]='\0';
        NSLog(@"%s is %lu characters long",word,strlen(word));
    }
    fclose(fp);
    return 0;
}*/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值