【问题标题】:c++ template class error when referencing implementation of class from inside the header file从头文件中引用类的实现时,c ++模板类错误
【发布时间】:2013-11-15 00:50:32
【问题描述】:

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

所以我正在做一个家庭作业来创建一个利用模板能够同时使用数字数据和字符串的堆类。我使用的编译器是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 << ' ';
}
}

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

【问题讨论】:

    标签: c++ visual-studio-2010 templates


    【解决方案1】:

    在定义成员函数时,不应在类中包含&lt;type&gt;。这样做:

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

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

    【讨论】:

    • 好吧,我试过了,但没有解决问题。我从头开始重新启动所有内容,创建了一个新的空项目,重新下载了文件,并且错误不再存在。所以我真的不确定我做了什么导致它。还可能值得注意的是,在我的 Heap.template 中,如果我在成员函数中省略 ,它实际上会给我一个错误,并且只有在我遵循 Heap::Function() 格式时才会编译。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-20
    • 2021-06-05
    • 2021-04-08
    相关资源
    最近更新 更多