扩展模板抽象类时出错

Error when extending a template abstract class

本文关键字:出错 抽象类 扩展      更新时间:2023-10-16

我有一个基于节点的队列实现的代码,我应该扩展一个名为QueueInterface的抽象类。

template<typename T>
struct QueueInterface {
    public:
    virtual ~QueueInterface(){};
    virtual bool isEmpty() const = 0;
    virtual void enqueue(const T value) = 0;
    virtual void dequeue() throw(PreconditionViolationException) = 0;
    virtual T peekFront() const throw(PreconditionViolationException) = 0;
};    
template<typename T>
struct Queue : QueueInterface {
    Queue();
    ~Queue();
    bool isEmpty() const;
    void enqueue(const T value);
    void dequeue() throw(PreconditionViolationException);
    T peekFront() const throw(PreconditionViolationException);
private:
    Node<T>* front;
    Node<T>* back;
};

我一直得到一个expected class name before '{' token错误,即使我包括了QueueInterface头文件。为什么会发生这种情况?

QueueInterface不是类。您可以从非结构或类的东西继承。这就是所谓的模板化类。您可以在模板化类之前使用template<...>来识别模板。您必须指定一个类型,以便编译器可以创建该类型的类。

在你的例子中,你正在尝试创建一个结构体,它也是一个模板。通过查看基类方法的重写,我猜您正在尝试这样做:

template<typename T>
struct Queue : QueueInterface<T> { 
    //   notice that there ---^--- you are sending the required parameter
    // defaulted members are good.
    Queue() = default;
    // override too.
    bool isEmpty() const override;
    void enqueue(const T value) override;
    void dequeue() throw(PreconditionViolationException) override;
    T peekFront() const throw(PreconditionViolationException) override;
private:
    Node<T>* front;
    Node<T>* back;
};