类的创建和初始化

来源:互联网 发布:2015中国石油进口数据 编辑:程序博客网 时间:2024/06/02 03:24
GirlFriend.h文件:

#import <Foundation/Foundation.h>
@interface car : NSObject
//NSObject是所有类的父类或者基类
//接口部分 新建的类继承于NSObject
{    //特征:实例变量,它起名字的时候加_
    @public//实例变量的可见度
    NSString *_type;
    NSString *_name;
    NSString *_date;
    NSInteger _age;/基本数据类型或者标量OC中别加*
}
//方法
- (void)length;
- (void)width;
- (void)height;
@end

GirlFriend.m文件:

#import "car.h"
@implementation car
-(instancetype)init
{
    _type = @"凯迪拉克";
    _name = @"第五代";
    _date = @"2015.1.1";
    _age = 1;
    return self;
}
- (void)length
{
    NSLog(@"汽车的长度为10m");
}
- (void)width
{
    NSLog(@"汽车的宽度为2m");
}
-(void)height
{
    NSLog(@"汽车的高度为3m");
}
@end

main.m文件

#import <Foundation/Foundation.h>
#import “car.h"

int main(int argc, const char * argv[]) {   
    //类和对象是面型对象的核心
    //类是具有相同特征和行为的事物的抽象
    //对象是类的实例 类是对象的类型
    //类包含两个部分接口和实现

car *c1 = [[car alloc]init];
    
    c1->_type = @"大众";
    c1->_name = @"Al6";
    c1->_date = @"2015年8月5日";
    c1->_age = 5;
    
    NSLog(@"%@", c1->_type);
    NSLog(@"%@",c1->_name);
    NSLog(@"%@",c1->_date);
    NSLog(@"%ld",c1->_age);
    
    [c1 length];
    [c1 width];
    [c1 height];
   return 0;
}

2015-08-11 18:02:27.626 OCLesson1_类和对象[2520:201672] 大众
2015-08-11 18:02:27.627 OCLesson1_类和对象[2520:201672] Al6
2015-08-11 18:02:27.627 OCLesson1_类和对象[2520:201672] 2015年8月5日
2015-08-11 18:02:27.627 OCLesson1_类和对象[2520:201672] 5
2015-08-11 18:02:27.627 OCLesson1_类和对象[2520:201672] 汽车的长度为10m
2015-08-11 18:02:27.627 OCLesson1_类和对象[2520:201672] 汽车的宽度为2m
2015-08-11 18:02:27.627 OCLesson1_类和对象[2520:201672] 汽车的高度为3m
Program ended with exit code: 0

0 0
原创粉丝点击