把ctor和非成员函数虚化

#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,然后这是一个妄图把非虚函数虚化
    上面其实有觉得,虚化这一过程,总是在他的派生类分出明细,在另一个非继承体系
    类来统一调用/实施,

*/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值