63 lines
1.5 KiB
C++
63 lines
1.5 KiB
C++
#include <iostream>
|
|
#include <memory>
|
|
#include <vector>
|
|
|
|
using namespace std;
|
|
|
|
class Shape {
|
|
public:
|
|
virtual shared_ptr<Shape> clone() = 0;
|
|
virtual void draw() = 0;
|
|
};
|
|
|
|
class Circle : public Shape {
|
|
int x;
|
|
int y;
|
|
int r;
|
|
public:
|
|
Circle(int x, int y, int r): x(x), y(y), r(r) {}
|
|
|
|
virtual shared_ptr<Shape> clone() override {
|
|
// Default copy using the copy constructor.
|
|
// You can customize this to perform deep or shallow copy as needed.
|
|
return std::make_shared<Circle>(*this);
|
|
}
|
|
|
|
virtual void draw() override {
|
|
cout << "draw " << x << " " << y << " " << r << endl;
|
|
}
|
|
};
|
|
|
|
class Square : public Shape {
|
|
int x1;
|
|
int y1;
|
|
int x2;
|
|
int y2;
|
|
public:
|
|
Square(int x1, int y1, int x2, int y2) : x1(x1), y1(y1), x2(x2), y2(y2) {}
|
|
|
|
virtual shared_ptr<Shape> clone() override {
|
|
return std::make_shared<Square>(*this);
|
|
}
|
|
|
|
virtual void draw() override {
|
|
cout << "draw " << x1 << " " << y1 << " " << x2 << " " << y2 << endl;
|
|
}
|
|
};
|
|
|
|
int main() {
|
|
shared_ptr<Shape> c = make_shared<Circle>(1, 2, 3);
|
|
shared_ptr<Shape> s = make_shared<Square>(1, 2, 3, 4);
|
|
|
|
vector<shared_ptr<Shape>> origin_shapes = {c, s};
|
|
vector<shared_ptr<Shape>> clone_shapes;
|
|
for (auto shape : origin_shapes) {
|
|
// You can clone without knowing the concrete type of shape.
|
|
clone_shapes.push_back(shape->clone());
|
|
}
|
|
|
|
for (auto shape : clone_shapes) {
|
|
shape->draw();
|
|
}
|
|
}
|