给出这个示例代码:
#include <iostream> #include <stdexcept> class my_exception_t : std::exception { public: explicit my_exception_t() { } virtual const char* what() const throw() { return "Hello,world!"; } }; int main() { try { throw my_exception_t(); } catch (const std::exception& error) { std::cerr << "Exception: " << error.what() << std::endl; } catch (...) { std::cerr << "Exception: unknown" << std::endl; } return 0; }
我得到以下输出:
Exception: unknown
然而,只是从std :: exception public继承my_exception_t,我得到以下输出:
Exception: Hello,world!
有人可以向我解释为什么继承类型在这种情况下是重要的?奖金积分,供参考.
解决方法
当您私有继承时,您无法转换为或以其他方式访问该类之外的基类.既然你要求标准的东西:
§11.2/4:
A base class is said to be accessible if an invented public member of the base class is accessible. If a base class is accessible,one can implicitly convert a pointer to a derived class to a pointer to that base class (4.10,4.11).
简单地说,对于类之外的任何东西,就像你从来没有继承过std :: exception,因为它是私有的. Ergo,它将无法被捕获在std :: exception&子句,因为不存在转换.