標籤:turn code class i++ operator include myarray main define
1 #define _CRT_SECURE_NO_WARNINGS 2 #include <iostream> 3 4 using namespace std; 5 6 class MyArray 7 { 8 public: 9 MyArray(int len); 10 ~MyArray(); 11 12 public: 13 int & operator[](int index); 14 int getlen(); 15 16 public: 17 class eSize 18 { 19 public: 20 eSize(int len) 21 { 22 size = len; 23 } 24 virtual void printfErr() 25 { 26 cout << "size:" << size <<endl; 27 } 28 protected: 29 int size; 30 private: 31 }; 32 33 class eNegative : public eSize 34 { 35 public: 36 eNegative(int size):eSize(size) 37 { 38 ; 39 } 40 virtual void printfErr() 41 { 42 cout << "eNegative 異常 size:" << size << endl; 43 } 44 protected: 45 private: 46 }; 47 class eZero : public eSize 48 { 49 public: 50 eZero(int size):eSize(size) 51 { 52 ; 53 } 54 virtual void printfErr() 55 { 56 cout << "eZero 異常 size:" << size << endl; 57 } 58 protected: 59 private: 60 }; 61 class eTooBig : public eSize 62 { 63 public: 64 eTooBig(int size):eSize(size) 65 { 66 ; 67 } 68 virtual void printfErr() 69 { 70 cout << "eTooBig 異常 size:" << size << endl; 71 } 72 protected: 73 private: 74 }; 75 class eTooSmall : public eSize 76 { 77 public: 78 eTooSmall(int size):eSize(size) 79 { 80 ; 81 } 82 virtual void printfErr() 83 { 84 cout << "eTooSmall 異常 size:" << size << endl; 85 } 86 protected: 87 private: 88 }; 89 90 91 protected: 92 private: 93 int *m_space; 94 int m_len; 95 }; 96 97 98 99 MyArray::MyArray(int len)100 {101 if (len < 0)102 {103 throw eNegative(len);104 }105 else if (len == 0)106 {107 throw eZero(len);108 }109 else if (len > 1000)110 {111 throw eTooBig(len);112 }113 else if (len < 3)114 {115 throw eTooSmall(len);116 }117 118 m_len = len;119 m_space = new int[len];120 }121 122 MyArray::~MyArray()123 {124 if (m_space != NULL)125 {126 delete[]m_space;127 m_space = NULL;128 m_len = 0;129 }130 131 }132 int& MyArray::operator[](int index)133 {134 return m_space[index];135 }136 int MyArray::getlen()137 {138 return m_len;139 }140 141 int main(void)142 {143 try144 {145 MyArray a(1);146 for (int i=0; i<a.getlen(); i++)147 {148 a[i] = i+1;149 printf("%d ", a[i]);150 }151 }152 catch (MyArray::eSize& e)153 {154 e.printfErr();155 }156 157 catch (...)158 {159 ;160 }161 162 163 164 cout << "Hello World!" << endl;165 system("pause");166 return 0;167 }
C++異常階層