设为首页 加入收藏

TOP

1.4.2 涉及其他ADT的ADT
2014-03-11 13:02:01 来源: 作者: 【 】 浏览:98
Tags:1.4.2 及其他 ADT

1.4.2  涉及其他ADT的ADT

前面的两个示例都需要表示日期,预约簿示例还要求表示时间。可以使用C++的ctime中的日期-时间对象表示日期和时间。也可以用面向对象的方式设计ADT表示这些项。设计使用其他ADT的ADT并不少见。实际上,可以使用一个ADT实现其他ADT。

注释:可以使用某个ADT实现其他ADT

最后一个示例描述一个ADT,该ADT的实现需要其他ADT。假定想要设计一个配方数据库。可以将这个数据库当作一个ADT。配方是数据项,某些针对配方的典型操作如下所示:
 

  1. // Inserts a recipe into the database.  
  2. +insertRecipe(aRecipe: Recipe): boolean  
  3. // Deletes a recipe from the database.  
  4. +deleteRecipe(aRecipe: Recipe): boolean  
  5. // Gets the named recipe from the database.  
  6. +getRecipe(name: string): Recipe  

这种层次的设计不会指明细节,例如insertRecipe将在数据库的什么位置放置某个配方。

现在假定想要设计操作,该操作按比例确定从数据库获取的配方大小:如果配方本来用于n个人,现在想要修改这个配方使其用于m个人。假定配方包含了度量单位,例如21/2杯、1汤匙和1/4茶匙。也就是说,份量使用混合数字(整数和分数)以杯、汤匙、茶匙为单位给定。

这个问题涉及另一个ADT(测量),该ADT具有的操作如下:
 

  1. // Returns this measure.  
  2. +getMeasure(): Measurement  
  3. // Sets this measure to another one.  
  4. +setMeasure(m: Measurement)  
  5. // Returns this measure multiplied by a fractional scale factor, which has no units.  
  6. +scaleMeasure(scaleFactor: float): Measurement  
  7. // Returns this measure converted from its old units to new units.  
  8. +convertMeasure(oldUnits: MeasureUnit,  
  9. newUnits: MeasureUnit): Measurement  

假定想让ADT测量执行准确的分数运算。由于我们计划使用的语言C++没有分数数据类型,而浮点数并不精确,因此就需要一个分数ADT。其操作可能包含分数的加、减、乘、除。例如,可以将加法指定为:
 

  1. // Returns the sum, reduced to lowest terms, of this fraction and the given fraction.  
  2. +add(other: Fraction): Fraction  

此外,当方便的时候,可以包含将混合数字转换为分数的操作以及反向操作。当最终实现了ADT测量时,可以使用ADT分数。也就是说,可以使用一个ADT实现另一个ADT。
 

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇1.4.1 设计ADT(2) 下一篇1.5.1 确定行为

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·Libevent C++ 高并发 (2025-12-26 00:49:30)
·C++ dll 设计接口时 (2025-12-26 00:49:28)
·透彻理解 C 语言指针 (2025-12-26 00:22:52)
·C语言指针详解 (经典 (2025-12-26 00:22:49)
·C 指针 | 菜鸟教程 (2025-12-26 00:22:46)