如何覆盖子类中的超类方法导致重写方法被超类类型的对象调用

时间:2014-12-30 22:18:00

标签: ios objective-c inheritance

一个例子是来自斯坦福大学cs193p的作业3:

-(int)match:(NSArray *)otherCards
{
int score = 0;

if ([otherCards count] == 1)
{
    playingCard *otherCard = [otherCards firstObject];
    if ([self.suit isEqualToString: otherCard.suit])
    {
        score = 1;
        NSLog(@"%d",score);
    }else if (self.rank == otherCard.rank)
    {
        score = 4;
    }
}

return score;
}

以上是在名为PlayingCard的卡的子类中实现方法。

- (int)match:(NSArray *)otherCards
{
int score = 0;

for (Card *cards in otherCards)
    if ([cards.contents isEqualToString:self.contents])
        score = 1;

return  score;
}

以上是卡片中匹配的实现。

-(void)chooseCardAtIndex:(NSUInteger)index
{
Card *card = [self cardAtIndex:index];

if (!card.isMatched)
{
    if (card.isChosen)
    {
        card.chosen = NO;
    }
    else
    {
        for (Card *otherCard in self.cards)
        {
            if (otherCard.isChosen && !otherCard.isMatched)
            {
                int matchScore = [card match:@[otherCard]];
                if (matchScore)
                {
                    self.score += matchScore * MATCH_BONUS;
                    card.matched = YES;
                    otherCard.matched = YES;
                }
                else
                {
                    otherCard.chosen = NO;
                    self.score -= MISMATCH_PENALTY;
                }
                break;
            }
        }
        self.score -= COST_TO_CHOOSE;
        card.chosen = YES;
    }
}
}

如上所示,方法匹配由Card实例调用而不是playCard,但结果遵循playCard的实现

1 个答案:

答案 0 :(得分:0)

我认为你需要一个虚拟基类,在superClass卡中

-(int)match:(NSArray *)otherCards
{
  // do nothing
}

你需要两个子类,比如PlayingCard,NormalCard。你应该在每个子类中实现这个函数。