c++ - 关于异常继承语法的一个问题

标签 c++ inheritance exception

我有以下表示堆栈的类。

template <class T>
class stack {
    ...
public:
    explicit stack(int max_size = 100);
    stack(const Stack& s);
    ~stack();
    stack& operator=(const Stack&);
    void push(const T& t);
    void pop();
    T& top();
    const T& top() const;
    int getSize() const;
    class Exception : public std::exception {};
    class Full : public Exception {};
    class Empty : public Exception {};
};

现在,我有第二个继承自堆栈的类。它很相似,但它有一个特殊的方法叫做 popConditional将元素弹出堆栈,直到堆栈的顶部元素满足通用条件。

如果没有这样的元素,我应该从名为 NotFound 的类中抛出异常继承自类 ExceptionStack 中定义.我的问题是什么是正确的语法:

template <class T>
class ConditionalStack : public Stack<T> {
public:
    class NotFound : public Exception {
        const char* what() const override { return "not found"; }
    };
};

或者

template <class T>
class ConditionalStack : public Stack<T> {
public:
    class NotFound : public Stack<T>::Exception {
        const char* what() const override { return "not found"; }
    };
};

如果第一个不正确,为什么会这样?不应该上课 Exception也会遗传吗?

最佳答案

由于 Exception 是从属名称,您应该使用第二个代码段。

关于c++ - 关于异常继承语法的一个问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57906624/

相关文章:

c++ - 每秒在 QGraphicsView 中移动图像

php - 方法链和类继承

c# - 接口(interface)、继承和多态性方面的问题

c# - 异常与特殊返回值

java - 我在 android 上使用 java 时遇到异常 (java.lang.NoClassDefFoundError),为什么?

c# - System.Drawing.Image 异常

c++ - 如何在编写模板模板函数时使用类型别名

c++ - C++ 函数参数中的求值顺序

c++ - 转换为 unix 时间戳不正确

ruby-on-rails - 使用基类与基模块重构 ActiveRecord 模型