std :: exception的C ++异常和继承 [英] C++ Exceptions and Inheritance from std::exception

查看:386
本文介绍了std :: exception的C ++异常和继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出此示例代码:

#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

继承 my_exception_t std :: exception public ,I得到以下输出:

Yet simply making the inheritance of my_exception_t from std::exception public, I get the following output:

Exception: Hello, world!

有人可以向我解释为什么这种类型的继承在这种情况下很重要吗?

Could someone please explain to me why the type of inheritance matters in this case? Bonus points for a reference in the standard.

推荐答案

当您私下继承时,您不能转换为或以其他方式访问该基类的类。由于您要求标准中的某些内容:

When you inherit privately, you cannot convert to or otherwise access that base class outside of the class. Since you asked for something from the standard:


§11.2/ 4:

基类被称为如果基类的发明的公共成员可访问,则可访问。如果一个基类是可访问的,可以隐式地将指向一个派生类的指针转换为指向该基类的指针(4.10,4.11)。

§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& 子句中,因为不存在转换。

Simply put, to anything outside the class it's like you never inherited from std::exception, because it's private. Ergo, it will not be able to be caught in the std::exception& clause, since no conversion exists.

这篇关于std :: exception的C ++异常和继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆