C++开发中级


849 浏览 5 years, 4 months

4.1 回到电子表格

版权声明: 转载请注明出处 http://www.codingsoho.com/

回到电子表格

前面使用电子表格程序作为示例来说明面向对象设计。SpreadsheetCell代表一个数据元素。这个元素可以是双精度值或者字符串。下面给出了一个简化的SpreadsheetCell类定义。注意单元格可以是双精度值或者字符串,然而这个示例中单元格的当前值总是以字符串形式返回。

class SpreadsheetCell
{
 public:

  SpreadsheetCell();
  virtual void set(double inDouble);
  virtual void set(const std::string& inString);
  virtual std::string getString() const;

 protected:
  static std::string doubleToString(double inValue);
  static double stringToDouble(const std::string & inString);
  double mValue;
  std::string mString;
};

前面的SpreadsheetCell类好像存在风险—有时候单元格是双精度值,有时候是字符串,有时候不得不在这两种格式之间转换。为了实现二元性,尽管给定的单元格只应该包含一个值,但是类还是需要存储两种值。更糟的是,如果单元格需要其他类型,例如公式单元格或者日期单元格,该怎么办?为了支持所有这些数据类型以及类型之间的转换,SpreadsheetCell类将会显著增长。