为什么这个程序没有捕获异常?

xiv*_*r77 6 c++ inheritance exception

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

#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());
    }
}
Run Code Online (Sandbox Code Playgroud)

Bar*_*rry 10

问题出在这里:

template<typename T>
class Blah : std::exception
//          ^^^^^^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)

您将私下继承(因为默认情况下class继承是private您没有添加说明符),因此std::exception不是可访问的基础.你必须公开继承.