基类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(); } };
时间: 2024-10-07 19:12:27