2014-12-30 100 views
-2

一个例子是来自斯坦福的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; 
} 

以上是实施CardCard的一个子类中的方法称为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; 
    } 
} 
} 

正如你可以在上面看到,该方法的比赛是由卡的一个实例调用,而不是游戏牌,然而结果如下执行从游戏牌

+1

https://en.wikipedia.org/wiki/Polymorphism_(computer_science) –

+0

没有调用的上下文,看到超类和子类的实现并没有给出任何迹象表明为什么你会得到意想不到的结果。尽管有这种意图,但很有可能你在该范围内有一张纸牌,而不是一张卡。 – adamdc78

+0

@ adamdc78我已经包含了调用的上下文。 – Google

回答

0

我想你需要一个虚基类,在超卡

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

并且您需要两个子类,如PlayingCard,NormalCard.YOU应该在每个子类中实现该函数。

相关问题