为什么该程序无法捕获异常?

xiver77

我正在尝试使用异常来打印类型名称,但是我的程序似乎没有捕获到异常,而是调用了默认终止函数。我错过了什么?

#include <cstdio>
#include <exception>
#include <typeinfo>

namespace Error
{
    template<typename T>
    class Blah : std::exception
    {
        virtual const char* what() const throw()
        {
            return typeid(T).name();
        }
    };
}

void blah() {
    throw Error::Blah<int*********>();
}

int main()
{
    try
    {
        blah();
    }
    catch (std::exception& e)
    {
        std::puts(e.what());
    }
}
巴里

问题在这里:

template<typename T>
class Blah : std::exception
//          ^^^^^^^^^^^^^^^

您正在私下继承(因为默认情况下class继承是private默认的,并且您不添加说明符),所以std::exception它不是可访问的基础。您必须公开继承。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章