Advertisement
irmantas_radavicius

Untitled

Mar 14th, 2024
564
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.90 KB | None | 0 0
  1. #include <iostream>
  2. #include <stdexcept>
  3.  
  4. #define MSG_POSITIVE "Dimensions have to be positive"
  5. #define MSG_UNEXPECTED "Unexpected error occurred"
  6.  
  7. using namespace std;
  8.  
  9. class Box {
  10.   private: 
  11.     int width;
  12.     int height;
  13.     int depth;
  14.   public:
  15.     // constructors
  16.     Box(int x, int y, int z){
  17.       setWidth(x);
  18.       setHeight(y);
  19.       setDepth(z);
  20.     }
  21.     // setters
  22.   public:
  23.     void setWidth(int width){
  24.       if(width > 0)
  25.         this->width = width;
  26.       else
  27.         throw invalid_argument(MSG_POSITIVE);
  28.     }
  29.     void setHeight(int height){
  30.       if(height > 0)
  31.         this->height = height;
  32.       else
  33.         throw invalid_argument(MSG_POSITIVE);
  34.     }
  35.     void setDepth(int depth){
  36.       if(depth > 0)
  37.         this->depth = depth;
  38.       else
  39.         throw invalid_argument(MSG_POSITIVE);
  40.     }
  41.    
  42.   public:
  43.     // getters
  44.     int getWidth(){
  45.       return this->width;
  46.     }
  47.     int getHeight(){
  48.       return this->height;
  49.     }
  50.     int getDepth(){
  51.       return this->depth;
  52.     }
  53.     string toString(){
  54.       string temp = "(";
  55.       temp += to_string(getWidth());
  56.       temp += ", " + to_string(getHeight());
  57.       temp += ", " + to_string(getDepth());
  58.       temp += ")";
  59.       return temp;
  60.     }
  61. };
  62.  
  63. int main() {
  64.   try {
  65.     Box box(1, 2, 3);
  66.     cout << box.toString() << endl;
  67.     box.setWidth(10);
  68.     cout << box.toString() << endl;
  69.     box.setWidth(-10);
  70.     cout << box.toString() << endl;
  71.  
  72.   } catch(exception &e){
  73.     cout << e.what() << endl;
  74.   } catch(...){
  75.     cout << MSG_UNEXPECTED << endl;
  76.   }
  77.  
  78.   try {
  79.     Box box(10, -20, 30);
  80.     cout << box.toString() << endl;
  81.     box.setWidth(10);
  82.     cout << box.toString() << endl;
  83.     box.setWidth(-10);
  84.     cout << box.toString() << endl;
  85.  
  86.   } catch(exception &e){
  87.     cout << e.what() << endl;
  88.   } catch(...){
  89.     cout << MSG_UNEXPECTED << endl;
  90.   }
  91.   return 0;
  92. }
  93.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement