C++技术之虚化拷贝构造函数

一、虚函数返回类型的语法规则

当子类(derived class)实现父类(base class)的一个虚函数时,不在一定得声明与原本形同的返回类型。如果函数的返回类型是一个指针或者引用,指向父类(base class),则子类(derived class)的函数可以返回一个指针或者引用指向该父类(base class)的一个子类(derived class)。

二、样例

#include <list>


struct NLComponent
{
    virtual NLComponent* clone() const = 0;
    // ...
};

struct TextBlock : NLComponent
{
    virtual TextBlock* clone() const override 
    {
        return new TextBlock(*this);
    }

    // ...
};

struct Graphic : NLComponent
{
    virtual Graphic* clone() const override 
    {
        return new Graphic(*this);
    }
    // ...
};


struct NewsLetter
{
    NewsLetter() = default;
    // 实现任何对象的copy
    NewsLetter(const NewsLetter& rhs)
    {
        for(auto& component : rhs.components)
        {
            components.push_back(component->clone());
        }
    }

    void add(NLComponent* component)
    {
        components.push_back(component);
    }

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


int main()
{
    NewsLetter newsLetter;
    newsLetter.add(new TextBlock());
    newsLetter.add(new Graphic());

    // copy
    NewsLetter backup(newsLetter);

    return 0;
}

通过利用虚函数函数返回值规则,实现NewsLetter对其聚合的任可类对象的拷贝。

猜你喜欢

转载自blog.csdn.net/xunye_dream/article/details/115036123