Last active
April 5, 2019 19:52
-
-
Save bluurn/6387bc7922610bbd7fb088adebf5b62d to your computer and use it in GitHub Desktop.
CPP: make_shared and shared_ptr demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <iomanip> | |
#include <vector> | |
#include <sstream> | |
#include <memory> | |
#include <cmath> | |
using namespace std; | |
const double PI = 3.14; | |
class Figure { | |
public: | |
virtual string Name() const = 0; | |
virtual double Perimeter() const = 0; | |
virtual double Area() const = 0; | |
}; | |
class Triangle : public Figure { | |
public: | |
Triangle(double a, double b, double c) : A(a), B(b), C(c) {} | |
virtual string Name() const override { return "TRIANGLE"; } | |
virtual double Perimeter() const override { return A + B + C; } | |
virtual double Area() const override { | |
double p = Perimeter() / 2; | |
return sqrt(p * (p - A) * (p - B) * (p - C)); | |
} | |
private: | |
double A; | |
double B; | |
double C; | |
}; | |
class Rect : public Figure { | |
public: | |
Rect(double w, double h) : W(w), H(h) {} | |
virtual string Name() const override { return "RECT"; } | |
virtual double Perimeter() const override { return (W + H) * 2; } | |
virtual double Area() const override { return W * H; } | |
private: | |
double W; | |
double H; | |
}; | |
class Circle : public Figure { | |
public: | |
Circle(double r) : R(r) {} | |
virtual string Name() const override { return "CIRCLE"; } | |
virtual double Perimeter() const override { return 2*PI*R; } | |
virtual double Area() const override { return PI*R*R; } | |
private: | |
double R; | |
}; | |
shared_ptr<Figure> CreateFigure(istringstream& is) { | |
string fig_name; | |
is >> fig_name; | |
if (fig_name == "RECT") { | |
double w, h; | |
is >> w >> h; | |
return make_shared<Rect>(w, h); | |
} else if (fig_name == "CIRCLE") { | |
double r; | |
is >> r; | |
return make_shared<Circle>(r); | |
} else if (fig_name == "TRIANGLE") { | |
double a, b, c; | |
is >> a >> b >> c; | |
return make_shared<Triangle>(a, b, c); | |
} else { | |
throw logic_error("Incorrect figure type"); | |
} | |
} | |
int main() { | |
vector<shared_ptr<Figure>> figures; | |
for (string line; getline(cin, line); ) { | |
istringstream is(line); | |
string command; | |
is >> command; | |
if (command == "ADD") { | |
figures.push_back(CreateFigure(is)); | |
} else if (command == "PRINT") { | |
for (const auto& current_figure : figures) { | |
cout << fixed << setprecision(3) | |
<< current_figure->Name() << " " | |
<< current_figure->Perimeter() << " " | |
<< current_figure->Area() << endl; | |
} | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment