继承与实例变量的混淆

时间:2013-07-16 03:23:24

标签: objective-c

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

/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?由于这些实例变量是在父类的继承文件中声明的,我不应该在子类中使用它们吗?我没有收到任何错误,所以我知道我们正在访问实例变量,但为什么我在运行时没有显示正确的值?

1 个答案:

答案 0 :(得分: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