为什么我不能使用父类的直接实例变量

时间:2013-03-16 08:34:29

标签: objective-c class

@interface rectangle: NSObject
@property int width, height;
{
     -(int) area;
     -(int) perimeter;
     -(void) setWidth: (int) w andHeight: (int) h;
}
@end

@implementation rectangle
@synthesize width, height;
...
...
@end

我制作了一个矩形

的方形子类
@interface square: rectangle
-(void) setSide: (int) s;
-(int) side;
@end


@implementation square
-(void) setSide: (int) s
{
    [self setWidth: s andHeight: s];
}
-(int) side
{
    return self.width;
}

@end

我的主要问题是:为什么我不能这样做

return width;

当我想要获得方形物体的一面时。 我想

@property int width, height;

只是一个简化的

@interface rectangle: NSObject
{
    int width;
    int height;
}
//getter/setter methods
...
@end

并且在书中,如果在@interface中声明了一个实例变量,它的子类将继承它。但是,显然,

return width;

似乎不起作用。为什么会这样?

1 个答案:

答案 0 :(得分:3)

问题是属性的合成是实现的一部分,而不是接口。子类只能依赖于接口。

例如,@synthesize 可以指定不同的实例变量名称(例如@synthesize width = _my_funky_width;),子类无法知道实际的实例变量是什么

相关问题