fcamuso

Corso C++ 39 - costruttori

Jul 1st, 2026
31
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.37 KB | None | 0 0
  1. import std;
  2.  
  3. class Test {
  4.     public:
  5.         //Test() {}  dubbio: è forse incompleto?        
  6.         Test() = default; //nessun dubbio
  7.  
  8.  
  9.         Test(int x) : x{x} {}
  10.    
  11.     private:
  12.         int x{};
  13. };
  14.  
  15.  
  16. class PuntoQ1 {
  17.  
  18.     public:
  19.       const int sconto_fisso;
  20.      
  21.       //costruttore di default (senza parametri) esplicito
  22.       PuntoQ1(): sconto_fisso{0} { /* std::println("Chiamato il costruttore!");*/ }
  23.  
  24.       PuntoQ1(int x_val, int y_val, int sconto_fisso=0):
  25.         x{x_val >= 0 ? x_val : throw std::invalid_argument("x negativo")},
  26.         y{y_val >= 0 ? y_val : throw std::invalid_argument("y negativo")},
  27.         sconto_fisso{sconto_fisso}
  28.       {
  29.       /*  if (x_val < 0) throw std::invalid_argument("x negativo");
  30.           if (y_val < 0) throw std::invalid_argument("y negativo");*/
  31.  
  32.           //x=x_val;  //this->x = x
  33.           //y=y_val;
  34.       }
  35.  
  36.  
  37.     private:  
  38.       int x;
  39.       int y;
  40.    
  41. };
  42.  
  43. auto main() -> int
  44. {
  45.     PuntoQ1 p1;              //evitare
  46.     PuntoQ1 p2 = PuntoQ1();  //evitare    
  47.  
  48.     PuntoQ1 p3{};        //OK
  49.     auto p4 = PuntoQ1{}; //OK
  50.  
  51.     auto p5 = PuntoQ1{3,5};
  52.     auto p6 = PuntoQ1(3.8,5.1);
  53.  
  54.     try {
  55.         auto p7 = PuntoQ1{ 3,-5};
  56.     }
  57.     catch (std::invalid_argument eccezione)
  58.     {
  59.         std::println("{}", eccezione.what());
  60.     }  
  61.  
  62.     Test n = Test{};
  63.  
  64. }
  65.  
Advertisement
Add Comment
Please, Sign In to add comment