C++ Primer 5th笔记(chap 19 特殊工具与技术)异常类层次
生活随笔
收集整理的這篇文章主要介紹了
C++ Primer 5th笔记(chap 19 特殊工具与技术)异常类层次
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1.
- 類 exception 、 bad_cast 和 bad_alloc 定 義 了 默 認 構 造 函 數
- runtime_error 和 logic_error沒有默認構造函數, 但是有一個可以接受 C 風格字符串或者標準庫 string類型實參的構造函數
1.1 exception 定義的函數
- 拷貝構造函數
- 拷貝賦值運算符
- 一個虛析構函數
- 一個名為 what 的虛成員。
what 函數返回一個 const char*,該指針指向一個以null結尾的字符數組, 并且確保不會拋出任何異常
eg.
class out_of_stock:public std::runtime_error { public:explicit out_of_stock(const std::string &s):std::runtime_error(s){} }; class isbn_mismatch:public std::logic_error { public:explicit isbn_mismatch(const std::string &s):std::logic_error(s){}isbn_mismatch(const std::string &s,const std::string &rhs,const std::string &lhs): std::logic_error(s),left(lhs),right(rhs){}const std::string left,right; }1.2 使用我們自己的異常類型
Sales_data& Sales_data::operator+(const Sales_data& rhs) {if(isbn()!=rhs.isbn())throw isbn_mismatch("Wrong isbns",isbn(),rhs.isbn());units_sold+=rhs.units_sold;revenue+=rhs.revenue;return *this; }Sales_data item1,item2,sum; while(cin>>item1>>item2) {try{sum=item1+item2;}catch(const isbn_mismatch &e){cerr<<e.what()<<":left isbn("<<e.left<<")right isbn("<<e.right<<")"<<endl;} }總結
以上是生活随笔為你收集整理的C++ Primer 5th笔记(chap 19 特殊工具与技术)异常类层次的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++ Primer 5th笔记(cha
- 下一篇: C++ Primer 5th笔记(cha