1.5.4 使用ADT包
假定我们雇佣了一名程序员用C++实现ADT包,使用目前为止开发的接口和规范。如果假定这些规范足够清晰,可以让程序员完成这一实现,那么就可以在程序中使用包的操作而不必知道实现细节。也就是说,使用这个包不需要知道这名程序员如何实现它,只需要知道这个ADT包做什么。
下面的示例演示了如何使用包并假定拥有一个C++类Bag,这个类实现了程序清单1-1给出的C++抽象类BagInterface。
示例 假定您邀请了三位朋友到家观看电视上您最喜欢的足球队。在插播商业广告期间,进行了下面的游戏。从一副牌中,拿掉了整套梅花:梅花A,2,3,…,J,Q,以及K。从中随机选取6张牌放入包中,然后您的朋友猜测哪些牌在包中。每次他们猜测正确的时候,就从包中拿出这张牌。当包清空的时候,牌最多的朋友获胜。程序清单1-2显示了进行这个游戏的简单程序。
程序清单1-2 猜牌游戏程序
- #include <iostream> // For cout and cin
- #include <string> // For string objects
- #include "Bag.h" // For ADT bag
- using namespace std;
- int main()
- {
- string clubs[] = { "Joker", "Ace", "Two", "Three",
- "Four", "Five", "Six", "Seven",
- "Eight", "Nine", "Ten", "Jack",
- "Queen", "King" };
- // Create our bag to hold cards.
- Bag<string> grabBag;
- // Place six cards in the bag.
- grabBag.add(clubs[1]);
- grabBag.add(clubs[2]);
- grabBag.add(clubs[4]);
- grabBag.add(clubs[8]);
- grabBag.add(clubs[10]);
- grabBag.add(clubs[12]);
- // Get friend’s guess and check it.
- int guess = 0;
- while (!grabBag.isEmpty())
- {
- cout << "What is your guess "
- << "(1 for Ace to 13 for King):";
- cin >> guess;
- // Is card in the bag
- if (grabBag.contains(clubs[guess]))
- {
- // Good guess – remove card from the bag.
- cout << "You get the card!\n";
- grabBag.remove(clubs[guess]);
- }
- else
- {
- cout << "Sorry, card was not in the bag.\n";
- } // end if
- } // end while
- cout << "No more cards in the bag. Game over!\n";
- return 0;
- }; // end main
编程窍门:当设计了一个类之后,应该尝试编写代码在实现这个类之前使用这个类。您不但会看到设计是否能解决当前的问题,而且还可以测试您对设计的理解,并检测用来记录规范的注释。您可能会发现类设计或者规范中存在的问题,如果确实存在问题,那么可以修改设计和规范并尝试再次使用这个类。
问题2 什么是抽象数据类?
问题3 当设计ADT的时候,应该采取什么步骤?