1

我很困惑为什么我的实例变量在我的子类中不起作用,即使实例变量是在父类的接口文件中声明的。我的子类从父类继承了一个方法来定义实例变量。然后子类使用它自己的一种方法来显示实例变量的值但值为零?这是为什么?

/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-07-15 20:09:35.625 Rectangle6[900:303] a 和 b 分别为 0 和 0

为什么 a 和 b 为 0?由于这些实例变量是在父类的继承文件中声明的,难道我不能在子类中使用它们吗?我没有收到任何错误,所以我知道我们正在访问实例变量,但为什么我在运行时没有显示正确的值?

4

1 回答 1

1

您应该使用派生类对象调用基类方法和变量

#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

#import "Rectangle.h"

@implementation Rectangle
@synthesize width, height;

-(id)init
{
    if (self=[super init]) {

    }
    return self;
}

-(void)define{
    a = width;
    b = height;
}

@end

矩形 2

#import <Foundation/Foundation.h>
#import "Rectangle.h"

@interface Rectangle2 : Rectangle
@property int width, height;
-(void) show;
@end


#import "Rectangle2.h"

@implementation Rectangle2
@synthesize width, height;

-(id)init
{
    if (self=[super init]) {

    }
    return self;
}

-(void) show
{
    [super setHeight:10];
    [super setWidth:5];

    [super define];

    NSLog(@"the width and height are %i and %i", width, height);
    NSLog(@" a and b are %i and %i",a, b);
}

@end

主班

int main(int argc, char *argv[])
{
    @autoreleasepool {

        Rectangle2 * shape2;
        shape2 = [[Rectangle2 alloc] init];

        shape2.width =2;
        shape2.height = 3;

        [shape2 show];


        return(0);
    }
}

输出是:--------

2013-07-16 09:26:49.275 rec[894:11303] 宽度和高度是 2 和 3 2013-07-16 09:26:49.277 rec[894:11303] a 和 b 是 5 和 10

于 2013-07-16T03:53:33.550 回答