shushus

Спринт 7. Копирование объектов. Часть первая.

Jan 12th, 2023
169
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.51 KB | None | 0 0
  1. #include <cassert>
  2. #include <iostream>
  3. #include <string>
  4. #include <vector>
  5.  
  6. using namespace std;
  7.  
  8. class Tentacle {
  9. public:
  10.     explicit Tentacle(int id)
  11.         : id_(id)
  12.     {
  13.     }
  14.  
  15.     int GetId() const {
  16.         return id_;
  17.     }
  18.  
  19. private:
  20.     int id_ = 0;
  21. };
  22.  
  23. class Octopus {
  24. public:
  25.     Octopus() {
  26.         Tentacle* t = nullptr;
  27.         try {
  28.             for (int i = 1; i <= 8; ++i) {
  29.                 t = new Tentacle(i);
  30.                 tentacles_.push_back(t);
  31.  
  32.                 t = nullptr;
  33.             }
  34.         } catch (const bad_alloc&) {
  35.             Cleanup();
  36.             delete t;
  37.             throw;
  38.         }
  39.     }
  40.  
  41.     const Tentacle& GetTentacle(int index) const {
  42.         if (index < 0 || static_cast<size_t>(index) >= tentacles_.size()) {
  43.             throw out_of_range("Invalid tentacle index"s);
  44.         }
  45.         return *tentacles_[index];
  46.     }
  47.  
  48.     ~Octopus() {
  49.         Cleanup();
  50.     }
  51.  
  52. private:
  53.     void Cleanup() {
  54.         for (Tentacle* t : tentacles_) {
  55.             delete t;
  56.         }
  57.         tentacles_.clear();
  58.     }
  59.  
  60.     vector<Tentacle*> tentacles_;
  61. };
  62.  
  63. int main(){
  64.     {
  65.         Octopus oc1;
  66.         Octopus oc22 = oc1;
  67.         cout << "Tentacle id = "s << oc22.GetTentacle(5).GetId() << endl;
  68.         Octopus oc333 = oc1;
  69.         cout << "Tentacle id = "s << oc333.GetTentacle(5).GetId() << endl;
  70.         Octopus oc4444 = oc1;
  71.         cout << "Tentacle id = "s << oc4444.GetTentacle(5).GetId() << endl;
  72.     }
  73.     cout << "OK"s << endl;
  74. }
Advertisement
Add Comment
Please, Sign In to add comment