码迷,mamicode.com
首页 > 其他好文 > 详细

Covariant Returen Types(协变返回类型)

时间:2016-02-12 23:21:43      阅读:385      评论:0      收藏:0      [点我收藏+]

标签:

基类virtual func返回类型为某个类(class Super)的ptr或ref,子类重写的virtual func返回类型可改为该类子类(class Sub : public Super)的ptr或ref。

                                               技术分享

class Base
{
public:
    virtual Base* clone() const { return new Base(*this); }
    virtual ~Base() {}
};

class Derived : public Base
{
public:
    virtual Base* clone() const { return new Derived(*this); }
    virtual ~Derived() {}
};

int main()
{
    Derived d;
    Base* bPtr = d.clone();
    Derived* dPtr = dynamic_cast<Derived*>(bPtr);
    if(!dPtr) {
        delete dPtr;
        dPtr = nullptr;
        // throw exception ...
    }
    return 0;
}

改为:
......

class Derived : public Base
{
public:
    virtual Derived* clone() const { return new Derived(*this); }
    virtual ~Derived() {}
};

int main()
{
    Derived d;
    Derived* dPtr = d.clone();
    return 0;
}

                            技术分享

class Cherry {};

class BingCherry : public Cherry {};

class CherryTree
{
public:
    virtual Cherry* pick() const { return new Cherry(); }
};

class BingCherryTree : public CherryTree
{
public:
    virtual BingCherry* pick() const { return new BingCherry(); }
};

 

Covariant Returen Types(协变返回类型)

标签:

原文地址:http://www.cnblogs.com/h3xi4oy1/p/5187316.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!