1. 程式人生 > >135.異常與類繼承

135.異常與類繼承

class error: row null pre () clu throw name

 1 #include <iostream>
 2 using namespace std;
 3 
 4 //如果產生繼承,子類的對象也可以被父類捕獲.因為子類內部包含父類對象
 5 class outerror
 6 {
 7 public:
 8 };
 9 
10 class newerror:public outerror
11 {
12 public:
13 };
14 
15 class myclass
16 {
17 private:
18     int *p;
19     int n;
20 
21 public:
22     myclass() :p(nullptr), n(0
) 23 { 24 25 } 26 27 myclass(int i) 28 { 29 if (i <= 0) 30 { 31 throw newerror(); 32 } 33 34 p = new int[i]; 35 for (int j = 0; j < i; j++) 36 { 37 p[j] = j; 38 } 39 } 40 41 int operator
[](int num) 42 { 43 if (num < 0) 44 { 45 throw newerror(); 46 } 47 48 if (num < 0 || num >= n - 1 || p == nullptr) 49 { 50 throw newerror(); 51 } 52 53 if (p == nullptr) 54 { 55 throw newerror();
56 } 57 return p[num]; 58 } 59 }; 60 61 void main() 62 { 63 try 64 { 65 myclass my1(1); 66 cout << my1[4]; 67 } 68 catch (outerror e) 69 { 70 cout << "outerror e" << endl; 71 } 72 catch (newerror e) 73 { 74 cout << "newerror e" << endl; 75 } 76 77 78 79 cin.get(); 80 }

135.異常與類繼承