都在这个例子里
class MyException: std::runtime_error // note, there is no public keyword in inheritance
{
public:
MyException(const std::string & x)
: std::runtime_error(x)
{}
};
int main( )
{
try
{
throw MyException("foo");
}
catch (std::exception & e )
{
std::cout << "catched std exception: " << e.what() << std::endl;
}
catch (...)
{
std::cout << "catched ... " << std::endl;
}
}
它在标准输出字符串“catched ...”上写入。但是,如果我将继承更改为 public 作为 class MyException : public std::runtime_error
,它会按预期工作(对我而言)并写入“catched std exception: foo”
c++ 标准的哪一部分要求这样的行为?为什么?在什么情况下这种行为可能有用?
最佳答案
有道理,符合重载决议的规则。在 MyException
之外,您的类不是 std::exception
。您应该将私有(private)继承视为一个实现细节(具有非常高的耦合度。)
在15.3处理异常中:
A handler is a match for an exception object of type E if
— The handler is of type cv T or cv T& and E and T are the same type (ignoring the top-level cv-qualifiers), or
— the handler is of type cv T or cv T& and T is an unambiguous public base class of E, or
— the handler is of type cv1 T* cv2 and E is a pointer type that can be converted to the type of the handler by either or both of - a standard pointer conversion (4.10) not involving conversions to pointers to private or protected or ambiguous classes — a qualification conversion
— the handler is a pointer or pointer to member type and E is std::nullptr_t.
(强调我的)
关于c++ - 从 std::runtime_error 私有(private)继承的类未被捕获为 std::exception,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27520673/