我很困惑,爲什麼我的實例變量不能在我的子類中工作,即使實例變量是在父類的接口文件中聲明的。我的子類繼承父類的方法來定義實例變量。然後子類使用其自己的方法之一來顯示實例變量的值,但值爲零?這是爲什麼?繼承混淆實例變量
/interface file of parent class **/
#import <Foundation/Foundation.h>
@interface Rectangle : NSObject
{
int w;
int h;
int j;
int k;
int a;
int b;
}
@property int width, height;
-(void) define;
@end
/**implementation file of parent class **/
#import "Rectangle.h"
@implementation Rectangle
@synthesize width, height;
-(void)define{
a = width;
b = height;
}
@end
/**interface file of subclass **/
#import "Rectangle.h"
@interface Rectangle2 : Rectangle
@property int width, height;
-(void) show;
@end
/**implementation file of subclass **/
#import "Rectangle2.h"
@implementation Rectangle2
@synthesize width, height;
-(void) show{
NSLog(@"the width and height are %i and %i", width, height);
NSLog(@" a and b are %i and %i", a, b);
}
@end
/**Main**/
#import "Rectangle.h"
#import "Rectangle2.h"
int main (int argc, const char * argv[])
{
@autoreleasepool {
Rectangle * shape1;
shape1 = [[Rectangle alloc] init];
Rectangle2 * shape2;
shape2 = [[Rectangle2 alloc] init];
shape1.width =10;
shape1.height = 5;
shape2.width =2;
shape2.height = 3;
[shape2 define];
[shape2 show];
}
return(0);
}
我的節目顯示以下內容:
Rectangle6 [900:303]的寬度和高度是2和3
2013年7月15日20:09:35.625 Rectangle6 [900:303 ] a和b是0和0
爲什麼a和b 0?由於這些實例變量是在父類的繼承文件中聲明的,因此我不應該能夠在子類中使用它們嗎?我沒有得到任何錯誤,所以我知道我們正在訪問實例變量,但爲什麼我在運行時不顯示正確的值?
我們可以看到這是如何用於其他課堂? – rezand
是的,請顯示子類。 – Fred
@rezand抱歉的傢伙,不知道你的意思。我不是在展示子類是如何工作的嗎?你能澄清你想讓我展示什麼嗎? – Brosef