fcamuso

Corso C++ 40 - delega tra costruttori

Jul 10th, 2026
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.80 KB | None | 0 0
  1. import std;
  2.  
  3. class PuntoQ1 {
  4.  
  5.    public:
  6.       PuntoQ1() = default; //per creare il punto (0,0)
  7.  
  8.       //costruttore 'standard' (configurazione parametri completa)
  9.       //definito anche costruttore 'target' per le deleghe
  10.       PuntoQ1(int x, int y):
  11.         x_{x >= 0 ? x : throw std::invalid_argument("x negativo")},
  12.         y_{y >= 0 ? y : throw std::invalid_argument("y negativo")}
  13.       {   }
  14.  
  15.       //costruttore che delega al precedente
  16.       //per creare un punto con coordinate uguali (sulla bisettrice)
  17.       PuntoQ1(int x) : PuntoQ1(x,x) {}
  18.  
  19.       //PuntoQ1(double x) : x_{x}, PuntoQ1(0,0) {} NO: o delega o inizializzazione
  20.  
  21.      
  22.      //costruttore che accetta stringhe
  23.      //esempio PuntoQ1( "(3, 6)" )
  24.      //(delegante)
  25.      PuntoQ1(const std::string& s) : PuntoQ1(
  26.           std::stoi(s.substr(1, s.find(',') - 1)),
  27.           std::stoi(s.substr(s.find(',') + 1))   //PuntoQ1(3,6)
  28.       ) {}
  29.  
  30.      //tag
  31.      struct Polare {};
  32.  
  33.      PuntoQ1(int raggio, int angolo_radianti, Polare p)
  34.          : PuntoQ1(raggio* std::cos(angolo_radianti),
  35.                    raggio* std::sin(angolo_radianti)) {}
  36.  
  37.  
  38.  
  39.  
  40.   //metodi getter / setter
  41.   [[nodiscard]] auto x() const -> int {return x_;}
  42.   [[nodiscard]] auto y() const -> int {return y_;}
  43.  
  44.   auto set_x(int x) -> void {
  45.  
  46.     if (x<0)
  47.         throw std::invalid_argument("x negativo");
  48.    
  49.     x_ = x;
  50.   }
  51.  
  52.     private:  
  53.       int x_{};
  54.       int y_{};
  55.       double x_{};
  56.    
  57. };
  58.  
  59. auto main() -> int
  60. {
  61.     auto p1 = PuntoQ1{10, 34}; //OK
  62.     std::println("{}", p1.x());
  63.  
  64.     std::string letta_da_file = "(12, 1)";
  65.     auto p2 = PuntoQ1(letta_da_file);
  66.  
  67.     std::println("{} {}", p2.x(), p2.y());
  68.  
  69.     auto p3 = PuntoQ1(12, 1, PuntoQ1::Polare{});
  70.     std::println("{} {}", p3.x(), p3.y());
  71.  
  72.  
  73.  
  74. }
  75.  
Advertisement
Add Comment
Please, Sign In to add comment