Naucz się C++ · lekcja 45 z 61 · około 11 minut
Projekt: Legowisko smoka
Zbuduj hierarchię wrogów, odrzucaj złych wrogów przez wyjątki i podawaj zagrożenie w legowisku przez jeden interfejs.
Czego się nauczysz
- Zaprojektować abstrakcyjną klasę bazową
- Sprawdzać dane w konstruktorach za pomocą wyjątków
- Przetwarzaj obiekty polimorficznie
Legowisko smoka
Na szczycie schodów jest legowisko smoka i bohater najpierw je zwiaduje. Każdy wróg to Enemy, klasa abstrakcyjna z czysto wirtualnymi threat() i kind(). Banda Goblins to 5 zagrożenia na każdego, a Dragon to 40 plus jego wiek; ich konstruktory rzucają std::invalid_argument dla liczby albo wieku poniżej 1, więc zły wróg nigdy nie powstaje. Bohater wpisuje wrogów takich jak goblins 3 aż do done, a przygoda wypisuje ich od najgroźniejszego do najmniej groźnego i mówi, czy suma jest mniejsza niż zdrowie bohatera.
Plan
Shapejest abstrakcyjna:area()iname()są czysto wirtualneRectangleiCircleje nadpisują i rzucają wyjątek, jeśli rozmiar nie jest dodatni- main tworzy kształty z linii takich jak
rect 3 4, pomija nieprawidłowe i wypisuje posortowany raport
Raport kształtów
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>
#include <vector>
class Shape {
public:
virtual ~Shape() = default;
virtual double area() const = 0;
virtual std::string name() const = 0;
};
class Rectangle : public Shape {
public:
Rectangle(double w, double h) : w_(w), h_(h) {
if (w <= 0 || h <= 0) throw std::invalid_argument("rectangle sides must be positive");
}
double area() const override { return w_ * h_; }
std::string name() const override { return "rectangle"; }
private:
double w_, h_;
};
class Circle : public Shape {
public:
explicit Circle(double r) : r_(r) {
if (r <= 0) throw std::invalid_argument("circle radius must be positive");
}
double area() const override { return 3.14159 * r_ * r_; }
std::string name() const override { return "circle"; }
private:
double r_;
};
int main() {
std::vector<std::unique_ptr<Shape>> shapes;
std::string kind;
while (std::cin >> kind) {
try {
if (kind == "rect") {
double w, h;
std::cin >> w >> h;
shapes.push_back(std::make_unique<Rectangle>(w, h));
} else if (kind == "circle") {
double r;
std::cin >> r;
shapes.push_back(std::make_unique<Circle>(r));
}
} catch (const std::invalid_argument& e) {
std::cout << "skipped: " << e.what() << "\n";
}
}
std::sort(shapes.begin(), shapes.end(), [](const auto& a, const auto& b) { return a->area() > b->area(); });
std::cout << std::fixed << std::setprecision(2);
for (const auto& s : shapes) std::cout << std::left << std::setw(10) << s->name() << s->area() << "\n";
}Wyjście
skipped: rectangle sides must be positive
circle 12.57
rectangle 12.00
circle 3.14Wskazówka
Rzucenie wyjątku z konstruktora oznacza, że nieprawidłowy obiekt w ogóle nie powstaje, więc każdy istniejący Shape jest na pewno poprawny.
Zachowanie kolejności przy remisach
std::sort może zamieniać równe elementy miejscami, więc dwaj wrogowie o takim samym zagrożeniu mogą wyjść w dowolnej kolejności. std::stable_sort przyjmuje te same argumenty i zachowuje równe elementy w kolejności dodania, dzięki czemu raport jest za każdym razem taki sam.
stable_sort
#include <algorithm>
#include <iostream>
#include <string>
#include <utility>
#include <vector>
int main() {
std::vector<std::pair<std::string, int>> v = {{"bats", 10}, {"ogre", 30}, {"rats", 10}};
std::stable_sort(v.begin(), v.end(), [](const auto& a, const auto& b) { return a.second > b.second; });
for (const auto& [name, threat] : v) std::cout << name << " " << threat << "\n";
}Wyjście
ogre 30
bats 10
rats 10Teraz spróbuj sam
Ta lekcja jest darmowa w Codiqo i ma 8 pytań o to, co właśnie przeczytałeś. Programowania uczy się, programując, więc kończy się krótkim programem, który piszesz sam, a my od razu go uruchamiamy i sprawdzamy.