Advertisement
Guest User

Untitled

a guest
Jun 23rd, 2017
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.45 KB | None | 0 0
  1. #include <iostream>
  2. #include <sstream>
  3. #include <string>
  4.  
  5. using namespace std;
  6.  
  7. class Exceptions{
  8. protected:
  9.     int n;
  10. public:
  11.     virtual string message() = 0;
  12. };
  13.  
  14. class OutOfRange : public Exceptions{
  15. public:
  16.     OutOfRange(int n){
  17.             this->n = n;
  18.     }
  19.     virtual string message(){
  20.         stringstream ss;
  21.         ss << "Podano indeks: " << n << ", ktory jest niepoprawny";
  22.         return ss.str();
  23.     }
  24. };
  25.  
  26. class BadAllocation : public Exceptions{
  27. public:
  28.     BadAllocation(int n){
  29.         this->n = n;
  30.     }
  31.     virtual string message(){
  32.         stringstream ss;
  33.         ss << "Podano zly rozmiar: " << n << ", nie mozna zaalokowac tablicy";
  34.         return ss.str();
  35.     }
  36. };
  37.  
  38. class Array{
  39. private:
  40.     int *tab;
  41.     int size;
  42. public:
  43.     Array(int s){
  44.         if(s <= 0)
  45.             throw BadAllocation(s);
  46.         tab = new int[s];
  47.         size = s;
  48.     }
  49.     ~Array(){
  50.         delete [] tab;
  51.     }
  52.     int get(int n){
  53.         if(n < 0 || n >= size)
  54.             throw OutOfRange(n);
  55.         return tab[n];
  56.     }
  57.     int & get_ref(int n){
  58.         if(n < 0 || n >= size)
  59.             throw OutOfRange(n);
  60.         return tab[n];
  61.     }
  62. };
  63.  
  64. int main(){
  65.     try{
  66.         Array tab(-2);
  67.         cout << tab.get(-1) << endl;
  68.     }
  69.     catch(BadAllocation & e1){
  70.         cout << e1.message() << endl;
  71.     }
  72.     catch(OutOfRange & e2){
  73.         cout << e2.message() << endl;
  74.     }
  75.     return 0;
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement