首页 > 解决方案 > C++ 异常抛出语法

问题描述

我目前正在阅读一本 C++ 书籍,遇到了这段我不知道如何解释的代码:

#include <exception>
#include <memory>
struct empty_stack: std::exception // don't know what the code after : means
{
     const char* what() const throw(); //don't understand this line either
};

标签: c++exception

解决方案


struct empty_stack: std::exception // don't know what the code after : means

这意味着empty_stack 公共继承std::exceptionwhich 是标准异常的基类。

注意:如果不指定继承类型,则默认继承类型取决于继承类型。如果private继承类型是classpublic如果继承类型是struct

const char* what() const throw(); //don't understand this line either

这意味着该what()函数不会修改它所属的类的非可变成员并且不会引发任何异常。throw()但是在结尾处表示它不会抛出 有点误导。

因此,从 C++11 开始,我们有了说明noexcept符。在像下面这样的函数声明中使用 this 意味着该函数被声明为不抛出任何异常。

const char* what() const noexcept;

注意throw()已弃用,将在 C++20 中删除。


推荐阅读