#include <iostream>
//virtual ctor
// first
class NLcomponent{
public:
virtual NLcomponent* clone() = 0;
//...
};
class TextBlock : public NLcomponent{
public:
virtual TextBlock* clone() { }
};
class Graphic : public NLcomponent{
public:
virtual Graphic* clone() { }
};
class NewLetter
{
public:
//...
private:
list<NLcomponent*>components;
};
////////////////////////////////////////////////////////////////////
//second
class NewLetter
{
public:
NewLetter(istream& str);
private:
list<NLcomponent*>components;
};
NewLetter::NewLetter(istream& str)
{
while(str)
components.push_back(readComponent(i_str));
//readComponent is a like ctor,请注意,NLcomponent是一个抽象基类
//构造函数的虚化我认为就是这里,
//...
}
////////////////////////////////////////////////////////////////////
//third ***copy ctor***
class NLcomponent{
public:
virtual NLcomponent* clone() = 0;
//...
};
class TextBlock : public NLcomponent{
public:
virtual TextBlock* clone()
{return new TextBlock(*this) }
};
class Graphic : public NLcomponent{
public:
virtual Graphic* clone()
{return new Graphic(*this) }
};
class NewLetter
{
public:
NewLetter(NewLetter&);
//...
private:
list<NLcomponent*>components;
};
NewLetter::NewLetter(NewLetter& rhs)
{
//迭代遍历rhs的list,运用每一个元素的virtual copy ctor
//讲元素复制到此对象的component list 中,一下代码的细节讨论
//
for(list<NewLetter>::const_iterator it = rhs.components.begin()
; it != rhs.end() ; it ++ )
{
components.push.back((*it)->clone);
//it只想当前元素,所以调用元素的clone函数取得元素的一个副本
//然后将副本加到component list尾端
}
}
//virtual non_fcn
// 简易版
class NLcomponent{
public:
virtual ostream& operator<< (ostream&) = 0;
//...
};
class TextBlock : public NLcomponent{
public:
virtual ostream& operator<< (ostream&) { }
};
class Graphic : public NLcomponent{
public:
virtual ostream& operator<< (ostream&) { }
};
// 并没有考虑class NewLetter
TextBlock T;
T<< cout;
// T.operator<<(cout);
/*
virtual ostream& operator<< (ostream& os)
{
//假设int i ==> mem_data
os << i ;
return *this;
}
*/
//完整版
class NLcomponent{
public:
virtual ostream& print (ostream&) = 0;
//...
};
class TextBlock : public NLcomponent{
public:
virtual ostream& print (ostream&) { }
};
class Graphic : public NLcomponent{
public:
virtual ostream& print (ostream&) { }
};
inline ostream& operator<<(ostream & os, NewLetter& c)
{
c.print(os);
}
/*首先,他可以inline,一般的虚函数是不能inline,然后这是一个妄图把非虚函数虚化
上面其实有觉得,虚化这一过程,总是在他的派生类分出明细,在另一个非继承体系
类来统一调用/实施,
*/
把ctor和非成员函数虚化
最新推荐文章于 2021-02-16 22:11:57 发布