【发布时间】:2020-08-23 23:28:29
【问题描述】:
我正在尝试构建一个简单的堆数据结构以供练习。当我为double 构建版本时,它工作正常。
class heapt {
public:
heapt();
heapt(std::initializer_list<double> lst);
void print_heapt();
private:
int size;
int length;
double* elem; //points to root
};
它的构造函数完美运行,堆被打印出来。但是当我尝试用
概括它时template< typename Elem>
作为:
template<typename Elem>
class heapt {
public:
heapt();
heapt(std::initializer_list<Elem> lst);
void print_heapt();
private:
int size;
int length;
Elem* elem; //points to root
};
对于类定义和 as:
template<typename Elem>
heapt<Elem>::heapt(std::initializer_list<Elem> lst) :
size{ static_cast<int>(lst.size()) },
elem{new Elem[lst.size()]}
{
std::copy(lst.begin(), lst.end(), elem);//Now heaptify elem
build_heapt(elem, lst.size());
}
用于主函数中使用的构造函数之一。
我收到两个链接错误:
LNK2019 函数 _main 中引用的未解析外部符号“public: void __thiscall heapt::print_heapt(void)”(?print_heapt@?$heapt@H@@QAEXXZ)
LNK2019 未解析的外部符号“public: __thiscall heapt::heapt(class std::initializer_list)”(??0?$heapt@H@@QAE@V?$initializer_list@H@ std@@@Z) 在函数 _main 中引用
主要功能是:
{
heapt<int> hh{ 27,12,3,13,2,4,14,5 };
std::cout << "Hello" << '\n';
hh.print_heapt();
}
编辑:heapt 类在“heap.h”文件中,构造函数heapt<Elem>::heapt(std::initializer_list<Elem> lst) 的定义在“heap.cpp”类中,其中有#include"heap.h"作为头文件。 int main 函数位于名为“InSo.cpp”的文件中,该文件还具有 #include"heap.h" 作为头文件。
【问题讨论】:
-
我怀疑:Q: Why can templates only be implemented in the header file? 很快就会出现在阅读列表中。当然,这纯粹是我的猜测,因为在发布的问题中没有提及哪些文件包含哪些代码,但这似乎很可能,所以我把它扔在那里。
-
@WhozCraig 成功了。我不知道使用模板需要将所有实现细节转移到头文件中。我将“heap.cpp”文件中的所有内容复制到“heap.h”文件中,现在编译没有错误。感谢您的帮助。
标签: c++ visual-studio compiler-errors linker lnk2019