【问题标题】:Objective-C Subclassing: Two subclass instances seem to point to the same instanceObjective-C 子类化:两个子类实例似乎指向同一个实例
【发布时间】:2012-06-03 14:05:52
【问题描述】:

当我执行下面的代码时,为什么我会收到底部列出的输出,我有点(实际上,很多)困惑。 Insect 和 Mammal 实例应该是具有不同实例变量的两个独立对象。对 [super initAttributes] 的两个调用都应该独立地初始化每个实例,每个实例都传递了 self。那么为什么 insectmammal 实例在显示时具有相同的值?似乎两个实例都指向内存中的同一个对象。

任何帮助将不胜感激。谢谢!

动物

//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

【问题讨论】:

  • 这是我的课,他们有 8 条腿。 :-)

标签: objective-c inheritance subclass


【解决方案1】:

我假设这是家庭作业,所以这里有一个提示: 错误在于您的变量声明。不要将全局变量用于多态性。

【讨论】:

  • 对于学习语言的人来说,这可能是一个非常微妙的问题。
  • @user1433587 Start here。具体来说,请阅读类实现部分,不要错过类接口部分中的注释。
  • 感谢您的回复!我正处于理解的风口浪尖。不是家庭作业;只是想学习Objective-C。我将查看 Apple Developer 网站以了解更多信息。
猜你喜欢
  • 1970-01-01
  • 2021-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-31
  • 2020-04-20
  • 1970-01-01
相关资源
最近更新 更多