第一篇blog就写写读书笔记吧。
constructor的虚化:
所谓virtual constructor,就是根据其输入,可以产生不同类型的对象。这个有点类似于工厂模式。 其本质上利用了虚函数返回类型的宽松点,即虚函数的返回类型可以是指向base class的指针或者引用。
Example:
class NLComponent
{
public:
virtual NLComponent *clone() const = 0;
...
};
class TextBlock : public NLComponent
{
public:
virtual TextBlock *clone() const
{ return new TextBlock(*this); }
};
class Graphic : public NLComponent
{
public:
virtual Graphic *clone() const
{ return new Graphic(*this); }
};
Non-member function的虚化:
原理很简单,但是未必人人都能想到并用好: 写一个虚函数做实际工作,在写一个仅调用这个虚函数的Non-member function. 可以利用inline来提高效率。
Example:
class NLComponent
{
public:
virtual ostream & print(ostream & s) const = 0;
};
class TextBlock : public NLComponent
{
public:
virtual ostream & print(ostream & s) const;
};
class Graphic : public NLComponent
{
public:
virtual ostream & print(ostream & s) const;
};
inline ostream & operator<<(ostream & s, const NLComponent & c)
{
return c.print(s);
}
That's all.
有空再写。