classShape { public: int x; int y; std::string color; Shape(int x, int y, const std::string& color): x(x), y(y), color(color) {} virtual Shape* clone()const= 0; virtual ~Shape() {} // 具有虚函数的基类中应该提供虚析构函数,确保通过基类指针删除派生类对象时,能够调用派生类析构函数! }
classRectangle: public Shape { public: int width; int height; Rectangle(int x, int y, const std::string color&, int width, int height): Shape(x, y, color), width(width), height(height){} Rectangle* clone()override{ returnnewRectangle(*this); } }
classCircle: public Shape { public: int radius; Circle(int x, int y, const std::string color&, int radius): Shape(x, y, color), radius(radius){} Circle* clone()override{ returnnewCircle(*this); } };
intmain(){ Circle c = Circle(10, 10, "#FFF", 5); Circle* pAnotherCircle = c.clone(); delete pAnotherCirlce; }