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 }