Covariant Returen Types(协变返回类型)

时间:2021-08-15 12:54:06

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

Covariant Returen Types(协变返回类型)

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 ...
    }
    ;
}

改为:
......

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

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

Covariant Returen Types(协变返回类型)

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(); }
};