1. 程式人生 > >136.異常的多態,父類對象,傳遞子類的引用或指針(地址)

136.異常的多態,父類對象,傳遞子類的引用或指針(地址)

else gpo () name pri clu 對象 col ror

 1 #include <iostream>
 2 using namespace std;
 3 
 4 //純虛類
 5 class error
 6 {
 7 public:
 8     //純虛函數
 9     virtual void showerror() = 0;
10 };
11 
12 class big :public error
13 {
14 public:
15     void showerror()
16     {
17         cout << "big error" << endl;
18     }
19     
20 };
21 22 class small :public error 23 { 24 public: 25 void showerror() 26 { 27 cout << "small error" << endl; 28 } 29 30 }; 31 32 class zero :public error 33 { 34 public: 35 void showerror() 36 { 37 cout << "zero error" << endl; 38 } 39 40
}; 41 42 //拋出一個引用對象 43 class print3d 44 { 45 public: 46 print3d(double size) 47 { 48 if (size == 0) 49 { 50 throw &zero(); 51 } 52 else if (size > 1000) 53 { 54 throw &big(); 55 } 56 else if (size < 1) 57
{ 58 throw &small(); 59 } 60 } 61 }; 62 63 void main() 64 { 65 try 66 { 67 print3d dg(0); 68 } 69 catch (error *p) 70 { 71 p->showerror(); 72 } 73 cin.get(); 74 }

136.異常的多態,父類對象,傳遞子類的引用或指針(地址)