使用模板类型参数时出错

Error using template type parameter

本文关键字:出错 类型参数      更新时间:2023-10-16

我在编译模板类时遇到了一些问题。我相信我正确地构造了骨架,但编译器不同意我的观点。我希望有人能看看这个,并指出我哪里出错了。

// 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

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

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