将构造函数和非成员函数虚化
遇到这个主题的时候,我们必须明白构造函数并没有实际的是虚函数,只是表现出了虚函数的行为而已,就是根据输入中的真实东西(而不是表面上的一些东西)执行相应的行为。
将构造函数虚化
将构造函数虚化主要分为两个部分,就是虚构造函数以及虚复制构造函数。
虚构造函数的主要用途在于从磁盘或网络构建对象的时候,我们来看下面的例子(用于处理新闻的类,其内容主要由文字以及图像构成,我们很容易设计出如下的类):
class NLComponent{...};//抽象基类,其中至少含有一个虚函数。
class TestBlock:public NLComponent { .. .};
class Graphics:public NLComponent { ... };
class NewsLetter
{
public:
NewsLetter(istream&str);
private:
static NLComponent *readComponent(istream &str);
List<NLComponent*> components;
}
NewsLetter::NewsLetter(istream&str)
{
while(str)
{
conponents.push_back(readcomponent(str));
}
}
注意NewsLetter可能存在与磁盘中,所以我们需要从磁盘中获取对象,就是调用NewsLetter的构造函数NewsLetter(istream&str);我们分析这个构造函数的行为,可以发现他的输入都是str,但是可以根据网络或者是磁盘输入的不同,而构建出不同的NewsLetter.这个功能就是被所谓的虚构造函数完成,我们看具体实现:readCompnent根据输入的不同而产生不同的对象,有了虚构造函数的行为,所以我们称这种函数为虚构造函数。
我们再来看虚复制构造函数
现在我们需要一个复制构造函数,形成NewsLetter的副本,由于其中NewsLetter的存储为list<NLComponent*> 这时候我们的实现代码,就可以使用虚构造函数的方式来实现,看具体代码:
class NLComponent
{
public:
virtual NLComponent* clone() const =0;
}
class TextBlock:public NLComponent
{
public:
virtual TextBlock* clone() const
{
return new TestBlock(*this);
}
}
class Graphic:public NLComponent
{
public:
virtual Graphic* clone () const
{
return new Graphic(*this);
}
}
这三个函数复制调用他的对象 根据对象的不同而产生不同的对象。利用这个虚复制构造函数我们可以很容易的实现NewsLetter的复制构造函数(这里是深度拷贝)
NewLetter::NewsLetter(NewsLetter&rhs)
{
for(auto it=rhs.component.begin();it!=rhs.components.end();it++)
{
components.push_back((*this)->clone());
}
}
将非成员函数虚拟化
将非成员函数虚拟化就是让非成员函数表现出虚函数的行为,基本的做法就是写一个虚函数做实际工作,再写一个什么都不做的非虚函数,只负责调用虚函数,就可以表现出虚函数的行为(这里吧外部的包裹函数inline化而避免函数调用的开销)具体的例子如下:
class NLComponent
{
public:
virtual ostream& print(ostream&) const =0;
}
class TextBlock:public NLComponent
{
public:
virtual osream& print(&) const
{
....
}
}
class Graphic:public NLCompent
{
public:
virtual ostream& print() const
{
...
}
}
inline osteam & operator<<(ostream&str ,NLComponent& c)
{
return c.print(str);
}
这里不管c实际是什么类型,都可以根据其实际类型打印,表现出虚函数的行为,所以我们说,利用这个手段将非成员函数虚拟化了。