标签:
基类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