1.5.4 使用ADT包

2014-03-11 12:59:54 · 作者: · 浏览: 121

1.5.4  使用ADT包

假定我们雇佣了一名程序员用C++实现ADT包,使用目前为止开发的接口和规范。如果假定这些规范足够清晰,可以让程序员完成这一实现,那么就可以在程序中使用包的操作而不必知道实现细节。也就是说,使用这个包不需要知道这名程序员如何实现它,只需要知道这个ADT包做什么。

下面的示例演示了如何使用包并假定拥有一个C++类Bag,这个类实现了程序清单1-1给出的C++抽象类BagInterface。

示例  假定您邀请了三位朋友到家观看电视上您最喜欢的足球队。在插播商业广告期间,进行了下面的游戏。从一副牌中,拿掉了整套梅花:梅花A,2,3,…,J,Q,以及K。从中随机选取6张牌放入包中,然后您的朋友猜测哪些牌在包中。每次他们猜测正确的时候,就从包中拿出这张牌。当包清空的时候,牌最多的朋友获胜。程序清单1-2显示了进行这个游戏的简单程序。

程序清单1-2  猜牌游戏程序
 

  1. #include <iostream>  // For cout and cin  
  2. #include <string>    // For string objects  
  3. #include "Bag.h"     // For ADT bag  
  4. using namespace std;  
  5. int main()  
  6. {  
  7. string clubs[] = { "Joker", "Ace", "Two", "Three",  
  8. "Four", "Five", "Six", "Seven",  
  9. "Eight", "Nine", "Ten", "Jack",  
  10. "Queen", "King" };  
  11. // Create our bag to hold cards.  
  12. Bag<string> grabBag;  
  13. // Place six cards in the bag.  
  14. grabBag.add(clubs[1]);  
  15. grabBag.add(clubs[2]);  
  16. grabBag.add(clubs[4]);  
  17. grabBag.add(clubs[8]);  
  18. grabBag.add(clubs[10]);  
  19. grabBag.add(clubs[12]);  
  20. // Get friend’s guess and check it.  
  21. int guess = 0;  
  22. while (!grabBag.isEmpty())  
  23. {  
  24. cout << "What is your guess "  
  25. << "(1 for Ace to 13 for King):";  
  26. cin >> guess;  
  27. // Is card in the bag  
  28. if (grabBag.contains(clubs[guess]))  
  29. {  
  30. // Good guess – remove card from the bag.  
  31. cout << "You get the card!\n";  
  32. grabBag.remove(clubs[guess]);  
  33. }  
  34. else  
  35. {  
  36. cout << "Sorry, card was not in the bag.\n";  
  37. } // end if  
  38. }   // end while  
  39. cout << "No more cards in the bag. Game over!\n";  
  40. return 0;  
  41. }; // end main  

编程窍门:当设计了一个类之后,应该尝试编写代码在实现这个类之前使用这个类。您不但会看到设计是否能解决当前的问题,而且还可以测试您对设计的理解,并检测用来记录规范的注释。您可能会发现类设计或者规范中存在的问题,如果确实存在问题,那么可以修改设计和规范并尝试再次使用这个类。

问题2 什么是抽象数据类?

问题3 当设计ADT的时候,应该采取什么步骤?