本章讲的是一个简单的打印案例,完全可用几行代码来完成,而面对问题不断复杂化,我们发现修改过程式的代码不足以支撑需求的多变。
作者构造了Picture类,汇总需求细节,见招拆招,尤其在“接口设计”这一节里,把自己当成客户,跟自己一问一答(“我希望有些什么操作,如何表述这些操作?”),逐步分析不断复杂的需求,然后抽象出接口,其中不乏作者的经验之谈:要想决定具体操作的形式,有一个好办法,就是试着使用这些操作,从使用的例子推导出操作的定义形式要比从头苦思冥想地发明这些操作容易得多。
1、最初需求是打印如下文字:
Paris
in the
Spring
2、构造的Picture类,只需要一个构造函数和一个输出即可完成,如果打印如下文字:
+-------+
|Paris |
|in the |
|Spring|
+-------+
3、如果使用C式的过程代码,需要做些打印内容的改变可以完成,作者为Picture类添加了一个frame(Picture&)来完成,如果打印内容改变了,我想C式代码作者就会抓头皮了:
Paris +-------+
in the |Paris |
Spring|in the |
|Spring|
+-------+
4、Picture类便有了 Picture operator |(const Picture&, const Picture&) 接口,用字符‘|’做两个Picture对象的横向合并,用Picture operator &(const Picture&,const Picture&)接口,用字符‘&’做纵向合并,当我们需要打印如下文字的时候:
+--------------+
|+------+ |
||Paris | |
||in the| |
||Spring| |
|+------+ |
|Paris +------+|
|in the|Paris ||
|Spring|in the||
| |Spring||
| +------+|
+--------------+
我们只需要一句 cout << frame(frame(p) & (p | frame(p))) << endl即可完成。
下面是Picture类的源码(原书代码中有些许错误,均做过修改和测试):
1 #include
2
3
4 using namespace std;
5
6 class Picture
7 {
8 friend Picture frame(const Picture&); //加框
9 friend Picture operator&(const Picture&, const Picture&); //纵向合并
10 friend Picture operator|(const Picture&, const Picture&); //横向合并
11 friend ostream& operator << (ostream& o, const Picture& p);
12 private:
13 int height, width;
14 char* data;
15 char& position(int row, int col){
16 return data[row * width + col];
17 };