当温迪和我回到办公室时,我坐在计算机旁,相当轻松就整理出基类:
class Base
{
private:
// … 一些数据,与本主题无关 …
virtual std::string classID() const { return "Base"; }
protected:
// 当派生类装入自身后,应该调用该函数的父类实现。
virtual void do_read( std::istream& );
// 当派生类保存完自身后,应该调用该函数的父类实现。
virtual void do_write( std::ostream& ) const;
public:
// … 需要实现的一些虚拟函数,与本主题无关…
// Streaming functions.
void read( std::istream& );
void write( std::ostream& ) const;
virtual ~Base();
};
// 流处理过程中的几个帮助函数。注意它们并非友元!
std::ostream& operator <<
( std::ostream& o, const Base& b) { b.write(o); }
std::istream& operator >>
( std::istream& o, Base& b) { b.read(o); }
// [3]
“很好,我的孩子,”Guru的声音又在我的身后响起。我从椅子上蹦了起来,责怪自己怎会没有想到她的来访。她接着说:“把你的成果简单地跟我说说。”
“很简单,”等Guru坐到客椅上,我回答说,“通过重载的<<操作符,Base::write会被调用,这里是它的实现:”
void Base::write( std::ostream& o ) const
{
o << classID() << std::endl;
do_write(o);
}
“嗯,模板方法模式(Template Tethod pattern),”Guru点点头,“你真聪明,我的孩子[4]。”
