C++ Primer Chapter 18 作者: rin 时间: October 15, 2021 分类: C++ # Ch18 ## 18.1 Exception handling Exceptions: seperate problem detection from problem resolution - Thrown expression & current call chain -> determine which handler - if a dtor wants to throw exceptions, it should handle them locally, or the program will be terminated. - When search for `catch`, the *first* matched one is selected, not the best one. - Thus catch clauses with class types must be orderd from the *most* derived one to *least* one. - Conversions (between exception and "a catch exception declaration") only allowed when: 1. from *non-const* to *const* 2. from *derived* to *base* 3. *array*/*function* to *pointer* ### function `try` block - `try` is before `: [init list]` - will catch exceptions both in *init list* and *ctor body* - An *implict* `throw` will be there, thus we HAVE to catch again in the outter scope - (thus it seems useless) ```c++ // function try block in Class struct A { A(int v) try : a(v) { throw exception(); } catch(exception &e) { cout << e.what() << endl; // implicit "throw;" here } int a; }; // in ordinary function void func() try { throw "ordinary func throws"; } catch(const char *s) { cout << s << endl; } // Notice: parameter here must be `const char*` to recieve the thrown c-str // or there will be a runtime error (not a compile-time error) int main() { func(); // must handle the rethrown exception try { A a(1); } catch(exception &e) { cout << e.what() << endl; } return 0; } ``` ## 18.2 Namespaces 1. `using` Declaration: `using std::cin` 2. `using` Directive: `using namespace std` - Inside a class can only `using` members of its (direct or not) *base class*: ```c++ using std::cout; struct A{ int v=0; }; struct B{ int v = 1; // using std::cin; // NO, not class // using A::v; // NO, not base // using namespace xxx; // NO, for `using` Directive either }; struct C: public B { using B::v; // OK `using` base class members C() { cout << v << '\n';} // 1 }; ``` ## 18.3 Multiple and Virtual Inheritance ### 18.3.2 Conversion ```c++ // D1 -> A,B // D2 -> C -> A struct A {}; struct B {}; struct D1 : A,B {}; struct C : A{}; struct D2 : C {}; void func(A &a); // func1 void func(B &b); // func2 void func(C &c); // func3 int main() { D1 d1; D2 d2; func(d1); // Ambiguous between 1 & 2 func(d2); // OK, 3, not 1 } ``` 标签: C++