我在编译模板类时遇到了一些问题。我相信我正在正确构建骨架,但编译器不同意我的看法。我希望有人可以看看这个并指出我出错的正确方向。
// 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 T
和 int MAX_SIZE
定义了参数,并且,就像常规变量一样(不是说 T
是一个变量),一旦它们'定义所有你需要的是使用它们的名称:
template<class T, int MAX_SIZE>
PQueue<T, MAX_SIZE>::PQueue() {
buildHeap();
}
关于c++ - 使用模板类型参数时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27030713/