const修饰this指针的用法

  1 #include <iostream>
  2 #include <string>
  3 
  4 using namespace std;
  5 
  6 class Base
  7 {
  8 };
  9 
 10 class Exception : public Base
 11 {
 12     int m_id;
 13     string m_desc;
 14 public:
 15     Exception(int id, string desc)
 16     {
 17         m_id = id;
 18         m_desc = desc;
 19     }
 20     
 21     int id() const
 22     {
 23         return m_id;
 24     }
 25     
 26     string description() const
 27     {
 28         return m_desc;
 29     }
 30 };
 31 
 32 
 33 /*
 34     假设: 当前的函数式第三方库中的函数,因此,我们无法修改源代码
 35     
 36     函数名: void func(int i)
 37     抛出异常的类型: int
 38                         -1 ==》 参数异常
 39                         -2 ==》 运行异常
 40                         -3 ==》 超时异常
 41 */
 42 void func(int i)
 43 {
 44     if( i < 0 )
 45     {
 46         throw -1;
 47     }
 48     
 49     if( i > 100 )
 50     {
 51         throw -2;
 52     }
 53     
 54     if( i == 11 )
 55     {
 56         throw -3;
 57     }
 58     
 59     cout << "Run func..." << endl;
 60 }
 61 
 62 void MyFunc(int i)
 63 {
 64     try
 65     {
 66         func(i);
 67     }
 68     catch(int i)
 69     {
 70         switch(i)
 71         {
 72             case -1:
 73                 throw Exception(-1, "Invalid Parameter");
 74                 break;
 75             case -2:
 76                 throw Exception(-2, "Runtime Exception");
 77                 break;
 78             case -3:
 79                 throw Exception(-3, "Timeout Exception");
 80                 break;
 81         }
 82     }
 83 }
 84 
 85 int main(int argc, char *argv[])
 86 {
 87     try
 88     {
 89         MyFunc(11);c
 90     }
 91     catch(const Exception& e)
 92     {
 93         cout << "Exception Info: " << endl;
 94         cout << "   ID: " << e.id() << endl;
 95         cout << "   Description: " << e.description() << endl;
 96     }
 97     catch(const Base& e)
 98     {
 99         cout << "catch(const Base& e)" << endl;
100     }
101     
102     return 0;
103 }

猜你喜欢

转载自www.cnblogs.com/DXGG-Bond/p/12264253.html
今日推荐