c++ - 使用模板类型参数时出错

标签 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

最佳答案

class Tint MAX_SIZE 定义了参数,并且,就像常规变量一样(不是说 T 是一个变量),一旦它们'定义所有你需要的是使用它们的名称:

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

关于c++ - 使用模板类型参数时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27030713/

相关文章:

ios - 将 ZIPArchive for iOS 添加到 xcode 时如何修复 'unknown type name' 错误

c++ - 随机生成的排序数组 : search performances comparison

c++ - 用 Go 构建包装 C++

c++ - 在模板方法c++中传递结构参数

c++ - 动态数组的运算符重载给出奇怪的错误

c++ - 为什么我收到 undefined reference 错误

c++ - Qt应用程序发布exe未运行

c++ - 不完整类型的 std::unique_ptr 无法编译

ios - 使用复选框自定义 XCode 文件模板

c++ - 创建模板化对象时替代工厂模式 - C++