【发布时间】:2011-02-06 17:36:59
【问题描述】:
我一直在阅读这个问题,但没有得到它遇到的问题。 why does initializing subclasses require calling the super class's same init function?
根据我的阅读和理解。每个类都有自己设计的初始化程序。 在这种情况下,如果一个类有几个初始化器。假设我有一个像这样的“Shape.h”类。
- (id) init
{
return [self initWithHeight: 0];
}
- (id) initWithHeight: (int) h
{
return [self initWithHeight:h withWidth:0];
}
- (id) initWithHeight: (int) h withWidth: (int) w
{
if(self = [super init]); //since the superclass is NSObject, I use init as designated initializer
{
[self setHeight:h];
[self setWidth:w];
}
return self
}
我从“Shape.h”类中继承了一个名为“Rectangle.h”的新类。 由于我将“Shape.h”指定为“-(id) initWithHeight: (int) h andWitdh: (int) w”,这意味着我需要将它用于“Rectangle.h”中的 [super init] “上课对吧?变成了这个样子。
- (id) initWithHeight: (int) h withWidth: (int) w
{
return [self initWithHeight: h withWidth: w withColor:nil];
}
- (id) initWithHeight: (int) h withWidth: (int) w withColor: (NSString *) c
{
if(self = [super initWithHeight:h andWidth:w])
{
[self setHeight:h];
[self setWidth:w];
[self setColor:c];
}
return self;
}
在“Rectangle.h”中,我覆盖了指定 init 的 super(即 Shape.h)并自定义它以适应“Rectangle.h”指定的类。这种工作方式是否正确并且不会导致循环?如果是这样,任何人都可以在发布的链接中向我解释为什么如果我使用 [super init] 而不遵循指定的超类 init 会循环。
如果我造成任何混乱,我很抱歉。我不能很好地理解这个概念。
【问题讨论】:
标签: objective-c