fcamuso

Corso C++ 44: this

Jul 30th, 2026
28
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.97 KB | None | 0 0
  1. import std;
  2.  
  3. class MyString {
  4.     std::string testo;
  5.  
  6. public:
  7.     MyString(const std::string& str) : testo{ str } {}
  8.  
  9.     auto rimuovi_spazi() -> MyString& {
  10.         std::erase(testo, ' ');
  11.         return *this;
  12.     }
  13.  
  14.     auto converti_maiuscolo() -> MyString& {
  15.         for (char& c : testo) {
  16.             c = std::toupper(static_cast<unsigned char>(c));
  17.         }
  18.         return *this;
  19.     }
  20.  
  21.     auto sostituisci(const std::string& da_cercare, const std::string& rimpiazzo) -> MyString& {
  22.         if (da_cercare.empty()) return *this;
  23.  
  24.         std::size_t pos = 0;
  25.         while ((pos = testo.find(da_cercare, pos)) != std::string::npos) {
  26.             testo.replace(pos, da_cercare.length(), rimpiazzo);
  27.             pos += rimpiazzo.length();
  28.         }
  29.         return *this;
  30.     }
  31.  
  32.     auto stampa() const -> void {
  33.         std::println("{}", testo);
  34.     }
  35. };
  36.  
  37. class Mostro {
  38.     public:
  39.         auto attacco(Personaggio& p) -> int
  40.         {
  41.             //logica in base al personaggio
  42.             //...
  43.             return 100; //il danno inflitto dal mostro
  44.         }
  45. };
  46.  
  47. class Personaggio {
  48.  
  49.     public:
  50.         Personaggio(int salute) : salute{salute} {}
  51.         auto interagisci(Mostro m) -> void
  52.         {
  53.            //logica che in base al mostro decide se e come attaccare
  54.            salute += m.attacco(*this);
  55.         }
  56.  
  57.         auto set_salute(int salute) -> void
  58.         {
  59.             //(*this).salute = salute;
  60.             this->salute = salute;
  61.         }
  62.  
  63.         //deducing this / self (prorogato)
  64.  
  65.     private:
  66.         int salute{1000};
  67.  
  68. };
  69.  
  70. int main() {
  71.     MyString stringa{ "  c i a o  m ondo A A A  " };
  72.  
  73.     MyString stringa2{ "seconda stringa" }, stringa3 {"terza stringa"};
  74.  
  75.     stringa2.rimuovi_spazi();
  76.  
  77.  
  78.     // Utilizzo del method chaining
  79.     stringa.rimuovi_spazi()
  80.         .converti_maiuscolo()
  81.         .sostituisci("A", "BBBBBB");
  82.  
  83.     stringa.stampa(); // Output atteso: CIBOMONDOBBB
  84.  
  85.     return 0;
  86. }
Advertisement
Add Comment
Please, Sign In to add comment