从头文件内部引用类的实现时,c++模板类错误

标签 c++ visual-studio-2010 templates

编辑:我从头开始重新启动所有内容后修复了它。我不确定是什么导致了这个问题。如果有人有任何想法,或了解导致主要问题的原因,我将编辑第一篇文章并进行跟进。

所以我正在做一个家庭作业来创建一个堆类,它利用一个模板来能够使用数字数据和字符串。我使用的编译器是visual studio 2010

头文件看起来是这样的..

#ifndef HEAP_H
#define HEAP_H

#include <iostream>
#include <vector>       // not needed if you use a static array

using std::cout;
using std::endl;
using std::vector;
template <typename type>
class Heap {
... the method headers I have to implement in the Heap.template file
};
#include "Heap.template"

#endif

Heap.template 文件是我们应该实现堆方法的地方。但是,我无法在不被错误杀死的情况下进行编译。这是讲师自己提供的第一种方法:

template <typename type>
Heap<type>::Heap(bool maxheap) {
// this default constructor supports a dynamic array. In this array, the root
// of the heap begins at index 1; the variable "dummy" is used to fill the 
// zero position of the dynamic array.  
type dummy;
  this->maxheap = maxheap;
  heap.push_back(dummy);
  size = heap.size()-1;
}

即使我注释掉了我已经实现的其余方法,我仍然会遇到错误

error C2143: syntax error : missing ';' before '<'
error C4430: missing type specifier - int assumed. Note: C++ does not support default-     int
error C2988: unrecognizable template declaration/definition
error C2059: syntax error : '<'

在线

Heap<type>::Heap(bool maxheap) {

我尝试在提供的 .template 文件中实现的每个方法都存在这些相同的错误集,例如这个打印方法

template <typename type>
void Heap<type>::PrintHeap()
{
for( std::vector<type>::iterator i = heap.begin(); i != heap.end(); ++i)
{
    cout << *i << ' ';
}
}

给我的错误与他提供的方法相同。我现在真的很困惑,真的不知道是什么导致了这个问题。我会很感激一些见解,谢谢!

最佳答案

你不应该包括 <type>当你定义成员函数时在你的类上。这样做:

template <typename type>
Heap::Heap(bool maxheap) {
    //...
}

由于 template,编译器已经知道该类使用这些模板参数声明。

关于从头文件内部引用类的实现时,c++模板类错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19991484/

相关文章:

c++ - 使用 BOOST.python 将结构从 C++ 返回到 Python

c++ - 将整数转换为位表示

c++ - V8 - Node C++ 插件 - 在 ConstructCall 中抛出异常导致 "FATAL ERROR: v8::ToLocalChecked Empty MaybeLocal."- 如何使构造函数失败?

c++ - 树的 DFS 递归,需要有关已访问问题的帮助

visual-studio-2010 - Visual Studio 2010 在启动时崩溃

c++ - 奇怪的模板构造函数语法

.net - Visual Studio 2010 无法识别 .NET Framework 4.0

visual-studio-2010 - VS 2010 多项目模板。你如何引用其他项目名称?

c++ - 枚举值的模板特化

c++ - 参数类型取决于结构内部的模板化结构的友元函数