使用模板类型参数时出错

时间:2014-11-20 02:31:53

标签: c++ templates compiler-errors

我在编译模板类时遇到了一些麻烦。我相信我正在构建骨架,但编译器不同意我的观点。我希望有人可以看看这个,并指出我正确的方向,我在哪里出错。

// default constructor, construct an empty heap
template<class T, int MAX_SIZE>
PQueue<class T, int MAX_SIZE>::PQueue() {
    buildHeap();
}

我在其他地方以同样的方式这样做,这些是我得到的错误:

PQueue.cpp:14:14: error: using template type parameter ‘T’ after ‘class’
 PQueue<class T, int MAX_SIZE>::PQueue() {
              ^
PQueue.cpp:14:29: error: template argument 1 is invalid
 PQueue<class T, int MAX_SIZE>::PQueue() {
                             ^
PQueue.cpp:14:29: error: template argument 2 is invalid
PQueue.cpp:14:39: error: declaration of template ‘template<class T, int MAX_SIZE> int PQueue()’
 PQueue<class T, int MAX_SIZE>::PQueue() {

仅供参考,这是我的头文件,我觉得很好:

#ifndef PRIORITY_QUEUE_H
#define PRIORITY_QUEUE_H

#include <iostream>
using namespace std;

// Minimal Priority Queue implemented with a binary heap
// Stores item of type T
template< class T, int MAX_SIZE >
class PQueue{
public:
    PQueue(); // default constructor, construct an empty heap
    PQueue(T* items, int size); // construct a heap from an array of elements
    void insert(T); // insert an item; duplicates are allowed.
    T findMin(); // return the smallest item from the queue
    void deleteMin(); // remove the smallest item from the queue
    bool isEmpty(); // test if the priority queue is logically empty
    int size(); // return queue size
private:
    int _size; // number of queue elements
    T _array[MAX_SIZE]; // the heap array, items are stoed starting at index 1
    void buildHeap(); // linear heap construction
    void moveDown(int); // move down element at given index
    void moveUp(); // move up the last element in the heap array
};

#include "PQueue.cpp"

#endif

1 个答案:

答案 0 :(得分:3)

class Tint MAX_SIZE定义参数,就像常规变量(不是T是一个变量)一样,一旦定义它们,您只需要使用的名称它们:

template<class T, int MAX_SIZE>
PQueue<T, MAX_SIZE>::PQueue() {
    buildHeap();
}
相关问题