typedef enum{
ColorBlack='b',ColorYellow='y',ColorWhite='w'
} Color;
#import<Foundation/Foundation.h>
@interface Pet : NSObject
{
@private
int _age;
double _weight;
NSString * _name;
}
- (id)initWithAge:(int)age andWeight:(double)weight andName:
(NSString *)name;
-(id)initTest;
- (NSString *)toString;
@end
@implementation Pet
// 重写init方法,由于是无参构造方法,无法动态给成员变量赋值
- (id)init
{
if(self=[super init]) //构造方法中必须调用父类构造方法
{
_age=1,_weight=1.0,_name=@"pet";
}
return self;
}
//自定义构造方法,可以自定义参数,灵活的给成员变量赋值
- (id)initWithAge:(int)age andWeight:(double)weight andName:(NSString *)name
{
if(self=[super init])
{
_age=age,_weight=weight,_name=name;
}
return self;
}
-(id)initTest
{
if(self=[super init])
{
//从结果可知,[super class],[self class]都是指向调用者的类对象
// 即若由Dog的实例调用,则都指向Dog的类对象,即[Dog class];
NSLog(@"super=%d,self=%d,superclass=%d,selfclass=%d,Pet=%d",
super,self,[super class],[self class],[Pet class]);
}
return self;
}
- (NSString *)toString
{
return [NSString stringWithFormat:@"name=%@ ,weight=%.2f ,age=%d",
_name,_weight,_age];
}
@end
@interface Dog : Pet
{
@private
Color _furColor;
}
- (id)initWithAge:(int)age andWeight:(double)weight andName:
(NSString *)name andFurColor:(Color)furColor;
@end
@implementation Dog
- (id)init
{
if(self=[super init])
{
_furColor=ColorYellow;
}
return self;
}
- (id)initWithAge:(int)age andWeight:(double)weight andName:
(NSString *)name andFurColor:(Color)furColor
{
//调用父类的有参构造方法给父类成员赋值
if(self=[super initWithAge:age andWeight:weight andName:name])
{
_furColor=furColor;
}
return self;
}
-(id)initTest
{
if(self=[super initTest])
{
NSLog(@"Dog=%d",[Dog class]);
}
return self;
}
- (NSString *)toString
{
return [NSString stringWithFormat:@"%@ ,furColor=%c",
[super toString],_furColor];
}
@end
int main()
{
//id作为万能指针,能指向任意OC对象
id *p=[[Dog alloc] init];
NSLog(@"this dog is %@",[p toString]);
id *p2=[[Dog alloc] initWithAge:4 andWeight:12.2 andName:@"Daisy"
andFurColor:ColorWhite];
NSLog(@"this dog is %@",[p2 toString]);
id *p3=[[Dog alloc] initTest];
NSLog(@"p3=%d",p3);
return 0;
}
/*
id关键字:
typedef struct objc_object {
Class isa;
} *id;
//构造对象相关方法伪代码
+ (id)new
{
return [[self alloc] init];
}
+ (id)alloc
{
id obj=(struct objc_object)malloc(父类到子类所有成员变量所占字节数总和);
return obj;
}
- (id)init
{
//[self class]返回类指针指向当前对象的类对象
isa=[self class];
return self;
}
//重写init方法必须调用[super init]来初始化父类中的成员变量 ---类似java无参constructor
- (id)init
{
if(self=[super init])
{
..初始化操作..
}
return self;
}
//自定义构造方法(一般以init开头) ---类似java有参构造器
- (id)initWithName:(NSString *)name
{
if(self=[super init])
{
_name=name;
}
return self;
}
*/
OC学习笔记04--id关键字与构造方法
最新推荐文章于 2024-02-01 21:48:07 发布