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