《More Effective C++》技术篇——将constr

2021-10-17  本文已影响0人  拉普拉斯妖kk
#include <iostream>
#include <list>

class NLComponent
{
public:
    // 声明 virtual copy constructor
    virtual NLComponent *clone() const = 0;

    virtual std::ostream& print(std::ostream& s) const = 0;

    NLComponent() {}
    virtual ~NLComponent() {}
};

class TextBlock : public NLComponent
{
public:
    // virtual copy constructor
    TextBlock *clone() const override {return new TextBlock(*this);}

    std::ostream& print(std::ostream& s) const override
    {
        s << "I'm TextBlock" << std::endl;
        return s;
    }
};

class Graphic : public NLComponent
{
public:
    // virtual copy constructor
    Graphic *clone() const override {return new Graphic(*this);}

    std::ostream& print(std::ostream& s) const override
    {
        s << "I'm Graphic" << std::endl;
        return s;
    }
};

// 将 Non-Member Function的行为虚化
inline std::ostream& operator<<(std::ostream& s, const NLComponent& c)
{
    return c.print(s);
}

class NewsLetter
{
public:
    NewsLetter() {}
    ~NewsLetter() {}

    // copy constructor
    NewsLetter(const NewsLetter& rhs);

    void AddComponet(NLComponent* c);
    void PrintComponents();

private:
    std::list<NLComponent*> components;
};

NewsLetter::NewsLetter(const NewsLetter& rhs)
{
    for (auto it = rhs.components.begin(); it != rhs.components.end(); it++)
    {
        components.push_back((*it)->clone());
    }
}

void NewsLetter::AddComponet(NLComponent* c)
{
    components.push_back(c);
}

void NewsLetter::PrintComponents()
{
    for (auto it = components.begin(); it != components.end(); it++)
    {
        std::cout << *(*it);
    }
}

int main()
{
    TextBlock tb;
    Graphic gp;
    NewsLetter nl1;
    nl1.AddComponet(&tb);
    nl1.AddComponet(&gp);
    NewsLetter nl2(nl1);
    nl2.PrintComponents();
}
上一篇 下一篇

猜你喜欢

热点阅读