0

以下のコードを実行すると、下にリストされている出力が表示される理由について、少し (実際にはかなり) 混乱しています。Insect インスタンスと Mammal インスタンスは、別々のインスタンス変数を持つ 2 つの別々のオブジェクトである必要があります。[super initAttributes] への両方の呼び出しは、各インスタンスを個別に初期化し、それぞれにselfを渡す必要があります。では、昆虫哺乳類の両方のインスタンスが表示されたときに同じ値になるのはなぜでしょうか? 両方のインスタンスがメモリ内の同じオブジェクトを指しているように見えます。

どんな助けでも大歓迎です。ありがとう!

動物クラス

//Interface

#import <Foundation/Foundation.h>

@interface Animal : NSObject

-(id) initAttributes: (NSString *) initName Legs: (int) initLegs Arms: (int) initArms;
-(void) display;

@end

//Implementation

#import "Animal.h"

@implementation Animal

NSString *name;
int legs, arms;

-(id) initAttributes: (NSString *) initName Legs: (int) initLegs Arms: (int) initArms
{
    self = [super init];

    if (self)
    {
        name = initName;
        legs = initLegs;
        arms = initArms;
    }

    return self;
}

-(void) display
{
    NSLog(@"Name: %@ Legs: %i Arms: %i", name, legs, arms);
}

@end

昆虫クラス

//Interface

#import "Animal.h"

@interface Insect : Animal

-(id) initInsect: (NSString *) initName;

@end

//Implementation

#import "Insect.h"

@implementation Insect

-(id) initInsect: (NSString *) initName
{
    self = [super initAttributes: initName Legs: 8 Arms: 0];

    if (self)
    {
    }

    return self;
}

@end

哺乳類クラス

//Interface

#import "Animal.h"

@interface Mammal : Animal

-(id) initMammal: (NSString *) initName;

@end

//Implementation


#import "Mammal.h"

@implementation Mammal

-(id) initMammal: (NSString *) initName
{
    self = [super initAttributes: initName Legs: 2 Arms: 2];

    if (self)
    {
    }

    return self;
}

@end

主要

#import <Foundation/Foundation.h>
#import "Insect.h"
#import "Mammal.h"

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

    @autoreleasepool {

        Insect *insect = [[Insect alloc] initInsect: @"Spydor"];
        Mammal *mammal = [[Mammal alloc] initMammal: @"Platypus"];

        [insect display];
        [mammal display];
    }

    return 0;
}

出力

名前:カモノハシ 足:2 腕:2
名前:カモノハシ 足:2 腕:2

4

1 に答える 1

1

これは宿題だと思いますので、ここにヒントがあります。エラーは変数宣言にあります。ポリモーフィズムにグローバル変数を使用しないでください。

于 2012-06-03T14:16:52.903 に答える