简体   繁体   English

如何声明模板类的析构函数

[英]How to declare destructor of a templated class

I get error while trying to compile following class 我在尝试编译下面的类时遇到错误

Stack.cpp:28: error: expected constructor, destructor, or type conversion before '::' token Stack.cpp:28:错误:在'::'标记之前的预期构造函数,析构函数或类型转换

#include <iostream>
using namespace std;

template <class T>
class Stack
{
public:
    Stack(): head(NULL) {};
    ~Stack();

    void push(T *);
    T* pop();

protected:
    class Element {
    public:
            Element(Element * next_, T * data_):next(next_), data(data_) {}
            Element * getNext() const { return next; }
            T * value() const {return data;}
    private:
            Element * next;
            T * data;
    };

    Element * head;
};

Stack::~Stack()
{
    while(head)
    {
            Element * next = head->getNext();
            delete head;
            head = next;
      }
 }

You are declaring a template class. 您正在声明模板类。 You can either: 你可以:

  • implement the destructor within the class declaration, like this 实现类声明的析构函数,这样

     public: Stack(): head(NULL) {}; ~Stack() { // ... } 
  • define the templated destructor outside the class declaration, like this 在类声明之外定义模板化析构函数,就像这样

     template <class T> Stack<T>::~Stack() { // ... } 

However, if you attempt to define just Stack::~Stack() then the compiler does not know which type T you are implementing the destructor for. 但是,如果您尝试仅定义Stack::~Stack()则编译器不知道您要为其实现析构函数的类型T

template<typename T>
Stack<T>::~Stack()
{
    //...
}

This is generally valid for every method you define outside of the class' declaration, not just the destructor. 这通常对您在类声明之外定义的每个方法都有效,而不仅仅是析构函数。

 Stack::~Stack()

should be 应该

template <typename T>
Stack<T>::~Stack()

If you put the function after the class definition, you must specify the template aspect again as in: 如果将函数放在类定义之后,则必须再次指定模板方面,如下所示:

template <class T>
Stack<T>::~Stack()
{
    ...
}

You don't need to do that if you define the function inside the class (but that constitutes a compiler hint to inline the function which you may or may not care about). 如果在类中定义函数,则不需要这样做(但这构成了编译器提示,以内联您可能或可能不关心的函数)。

不确定,但也许这样......

template <class T>

Stack<T>::~Stack()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM