多态继承虚函数与异常
1 /* 异常的继承与虚函数 */ 2 3 #include<iostream> 4 5 using namespace std; 6 7 class print3dbox 8 { 9 public: 10 print3dbox(int num) 11 { 12 if (num==0) 13 { 14 throw zero(1); 15 } 16 else if (num<10 && num>0) 17 { 18 throw small(); 19 } 20 else if (num>1000) 21 { 22 throw big(); 23 } 24 } 25 26 class small 27 { 28 29 }; 30 31 class big 32 { 33 34 }; 35 36 class zero:public small// 异常类可以派生 37 { 38 public: 39 int errorcode; 40 zero(int codeid):errorcode(codeid) 41 { 42 43 } 44 }; 45 46 private: 47 int x; 48 }; 49 50 void main() 51 { 52 try 53 { 54 print3dbox box(1); 55 } 56 catch (print3dbox::zero e) 57 { 58 cout << typeid(e).name() << endl; 59 } 60 catch (print3dbox::small e) 61 { 62 cout << typeid(e).name() << endl; 63 } 64 catch (print3dbox::big e) 65 { 66 cout << typeid(e).name() << endl; 67 } 68 } 69 70 //------------------------------------------------------------------------------- 71 72 73 /* 异常的多态与虚函数 */ 74 75 #include<iostream> 76 77 using namespace std; 78 79 class print3dbox 80 { 81 public: 82 print3dbox(int num) 83 { 84 error *p = nullptr;// 空指针 85 if (num==0) 86 { 87 p = new zeroerro; 88 throw p; 89 } 90 else if (num<10 && num>0) 91 { 92 p = new smallerror; 93 throw p; 94 } 95 else if (num>1000) 96 { 97 p = new bigerror; 98 throw p; 99 } 100 } 101 102 class error 103 { 104 public: 105 // virtual void showerror() = 0;// 直接设置成纯虚函数也可以 106 virtual void showerror() 107 { 108 cout << "virtual void showerror()" << endl; 109 } 110 }; 111 112 class bigerror:public error 113 { 114 public: 115 void showerror() 116 { 117 cout << "class bigerror void showerror()" << endl; 118 } 119 }; 120 121 class smallerror : public error 122 { 123 public: 124 void showerror() 125 { 126 cout << "class smallerror void showerror()" << endl; 127 } 128 }; 129 130 class zeroerro : public error 131 { 132 public: 133 void showerror() 134 { 135 cout << "class zeroerro void showerror()" << endl; 136 } 137 }; 138 139 private: 140 int x; 141 }; 142 143 void main() 144 { 145 try 146 { 147 print3dmax box(0); 148 } 149 catch (print3dmax::error *p) 150 { 151 p->showerror(); 152 } 153 154 cin.get(); 155 }
长风破浪会有时,直挂云帆济沧海
posted on 2015-06-16 14:21 Dragon-wuxl 阅读(99) 评论(0) 收藏 举报
浙公网安备 33010602011771号