C++ Primer 5th笔记(chap 19 特殊工具与技术)异常类层次
生活随笔
收集整理的這篇文章主要介紹了
C++ Primer 5th笔记(chap 19 特殊工具与技术)异常类层次
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
1.
- 類 exception 、 bad_cast 和 bad_alloc 定 義 了 默 認(rèn) 構(gòu) 造 函 數(shù)
- runtime_error 和 logic_error沒(méi)有默認(rèn)構(gòu)造函數(shù), 但是有一個(gè)可以接受 C 風(fēng)格字符串或者標(biāo)準(zhǔn)庫(kù) string類型實(shí)參的構(gòu)造函數(shù)
1.1 exception 定義的函數(shù)
- 拷貝構(gòu)造函數(shù)
- 拷貝賦值運(yùn)算符
- 一個(gè)虛析構(gòu)函數(shù)
- 一個(gè)名為 what 的虛成員。
what 函數(shù)返回一個(gè) const char*,該指針指向一個(gè)以null結(jié)尾的字符數(shù)組, 并且確保不會(huì)拋出任何異常
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;} }總結(jié)
以上是生活随笔為你收集整理的C++ Primer 5th笔记(chap 19 特殊工具与技术)异常类层次的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: C++ Primer 5th笔记(cha
- 下一篇: s3c2440移植MQTT