自定义构造函数 重写类描述,可以people *peoA=[[people alloc]init];直接输出NSLog(@"%@",peoA);

#import <Foundation/Foundation.h>

 

//自定义构造函数

@interface People : NSObject

{

#pragma mark 人类年龄

    NSInteger age;

#pragma mark 人类姓名

    NSString *name;

#pragma mark 人类身高

    NSInteger height;

}

 

//自定义构造函数 命名必须符合initXXX

//内部实现

//if(self = [super init])

//{

//    

//}

//return self;

 

 

/**

 *  初始化人类信息实例构造函数

 *

 *  @param newAge    人类年龄

 *  @param newName   人类姓名

 *  @param newHeight 人类身高

 *

 *  @return 人类对象

 */

- (id)initWithAge:(NSInteger)newAge

                    AndName:(NSString *)newName

                  AndHeight:(NSInteger)newHeight;

 

/**

 *  初始化人类信息类构造函数

 *

 *  @param newAge    人类年龄

 *  @param newName   人类姓名

 *  @param newHeight 人类身高

 *

 *  @return 人类对象

 */

+ (id)initWithAge:(NSInteger)newAge

                    AndName:(NSString *)newName

                  AndHeight:(NSInteger)newHeight;

 

- (void)display;

- (NSString *)description;

@end

 

 

#import "People.h"

 

@implementation People

 

/**

 *  初始化人类信息实例构造函数

 *

 *  @param newAge    人类年龄

 *  @param newName   人类姓名

 *  @param newHeight 人类身高

 *

 *  @return 人类对象

 */

- (id)initWithAge:(NSInteger)newAge

          AndName:(NSString *)newName

        AndHeight:(NSInteger)newHeight

{

    if(self = [super init])

    {

        age = newAge;

        name = newName;

        height = newHeight;

    }

    return self;

}

 

/**

 *  初始化人类信息类构造函数

 *

 *  @param newAge    人类年龄

 *  @param newName   人类姓名

 *  @param newHeight 人类身高

 *

 *  @return 人类对象

 */

+(id)initWithAge:(NSInteger)newAge

         AndName:(NSString *)newName

       AndHeight:(NSInteger)newHeight

{

    People *peo = [[People alloc]initWithAge:newAge

                                     AndName:newName

                                   AndHeight:newHeight];

    return peo;

}

 

- (void)display

{

    NSLog(@"name:%@,age:%ld,height:%ld",name,age,height);

}

 

/**

 *  类的描述,不重写的话是显示类的内存地址

 *

 *  @return 描述

 */

- (NSString *)description

{

    NSString *str = [NSStringstringWithFormat:@"name:%@,age:%ld,height:%ld",name,age,height];

    return str;

}

 

@end

 

#import <Foundation/Foundation.h>

#import "People.h"

 

int main(int argc, const char * argv[]) {

 

    @autoreleasepool {

        People *peoA = [[People alloc]init];

        People *peoB = [[People alloc]initWithAge:18

                                         AndName:@"旺财"

                                       AndHeight:189];

//  People *peoC = [People new]; 等同于  People *peoA = [[People alloc]init];

        

        NSLog(@"%@",peoA);

        NSLog(@"%@",peoB);

        

        People *peoC =  [People initWithAge:18 AndName:@"大黄" AndHeight:178];

        NSLog(@"%@",peoC);

    }

    return 0;

}

posted on 2016-04-16 14:10  小|晄  阅读(91)  评论(0编辑  收藏  举报

导航