인스턴스 변수가 부모 클래스의 인터페이스 파일에 선언 된 경우에도 내 인스턴스 변수가 내 하위 클래스에서 작동하지 않는 이유에 대해 혼란 스럽습니다. 내 하위 클래스는 부모 클래스의 메서드를 상속하여 인스턴스 변수를 정의합니다. 그런 다음 하위 클래스는 자체 메서드 중 하나를 사용하여 인스턴스 변수의 값을 표시하지만 값은 0입니까? 왜 그런가요? 09 : 35.625 Rectangle6 [900 : 303의 폭과 높이가 2와 3인스턴스 변수와 상속 혼란
부터 2013 년 20 같습니다
Rectangle6 [303 (900) :]
/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);
}
내 프로그램은 다음을 표시 ] a와 b는 0과 0이다.
a와 b는 왜 0인가? 이 인스턴스 변수는 부모 클래스의 상속 파일에서 선언되었으므로 하위 클래스에서 사용할 수 없습니까? 우리가 인스턴스 변수에 액세스하고 있다는 것을 알기 때문에 오류가 발생하지 않지만 실행시 올바른 값을 표시하지 않는 이유는 무엇입니까?
다른 클래스에서 이것이 어떻게 사용되는지 확인할 수 있습니까? – rezand
예, 서브 클래스를 보여주십시오. – Fred
@rezand 죄송합니다. 무슨 뜻인지 확실하지 않습니다. 하위 클래스가 어떻게 작동하는지 보여주지 않습니까? 내가 보여주고 싶은 것을 분명하게 해줄 수 있니? – Brosef