未解析的外部符号 -- 模板类
Unresolved External Symbol -- Template Class
可能的重复项:
C++模板,链接错误
我正在尝试实现选择排序,但不断收到错误(打印如下)。 在我看来,我所有的包含和模板都正确完成。 有人可以向我解释此错误的原因以及调试此类错误的一般方法。 它通常似乎发生在存在包含或模板问题时,但偶尔会发生在我不知道出了什么问题的情况下。 谢谢。
错误 LNK2019:未解析的外部符号"public: void __thiscall Selection::SelectionSort(int * const,int)"(?SelectionSort@?$Selection@H@@QAEXQAHH@Z) 在函数 _main 中引用
测试.cpp
#include <iostream>
#include "SelectionSort.h"
using namespace std;
void main()
{
int ar[] = {1,2,3,4,5};
Selection<int> s;
s.SelectionSort(ar,5);
for(int i = 0; i < 5; i++)
{
cout << "nstudent number " << i + 1<< " grade " << ar[i];
}
}
SelcectionSort.h
template<class ItemType>
class Selection
{
public:
void SelectionSort(ItemType[], int);
private:
int MinIndex(ItemType[], int, int);
void Swap(ItemType& , ItemType&);
};
选择排序.cpp
#include "SelectionSort.h"
template<class ItemType>
void Selection<ItemType>::SelectionSort(ItemType values[], int numValues)
// Post: The elements in the array values are sorted by key.
{
int endIndex = numValues-1;
for (int current = 0; current < endIndex; current++)
Swap(values[current],
values[MinIndex(values, current, endIndex)]);
}
template<class ItemType>
int Selection<ItemType>::MinIndex(ItemType values[], int startIndex, int endIndex)
// Post: Returns the index of the smallest value in
// values[startIndex]..values[endIndex].
{
int indexOfMin = startIndex;
for (int index = startIndex + 1; index <= endIndex; index++)
if (values[index] < values[indexOfMin])
indexOfMin = index;
return indexOfMin;
}
template<class ItemType>
inline void Selection<ItemType>::Swap(ItemType& item1, ItemType& item2)
// Post: Contents of item1 and item2 have been swapped.
{
ItemType tempItem;
tempItem = item1;
item1 = item2;
item2 = tempItem;
}
将SelectionSort.cpp
的内容移动到 SelectionSort.h
,就在类声明的正下方。还要确保在整个.h
文件的内容周围有一个标头保护。
问题来自C++如何实现模板。每次它看到与模板类一起使用的新类型(如 Selection<int>
),它都会重新创建整个类,并将ItemType
替换为 int
。
因此,它需要在编译时知道类的完整定义(及其方法)。它不能只使用类定义并将链接延迟到以后。
相关文章:
- C++:Application.cpp中抛出了未解析的外部符号(解决方案在问题的末尾,供未来的读者参考)
- 未解析的外部符号_MsiLocateComponentW@12.
- 在C++中使用 gRPC 时未解析的外部符号
- LibPrivoxy: 未解析的外部符号 __declspec(dllimport) int __stdcall Sta
- 尝试从 XamlApplication 编译 C++/WinRT 空白应用程序时,我收到未解析的外部符号 winrt_make_*
- 我收到错误LNK2001:未解析的外部符号(C++代码)
- 可视抽象类 c++(错误 LNK 2001:未解析的外部符号)
- 如何摆脱C++中未解析的外部符号"private: static char"错误?
- 当 lib 已添加到其他依赖项时,如何在 VS 中调试未解析的外部符号错误
- 仅在少数方法(静态或共享库)中解析的外部符号
- 未解析的外部符号"__declspec(dllimport)与 Spdlog c++ 库
- 函数 _main (OPENGL C++) 中引用的未解析的外部符号 ________
- 错误LNK2019未解析的外部符号"public: __thiscall SLinkList<char>::SLinkList<char>(void)"
- 使用静态 constexpr 成员的未解析外部符号
- 引入参数化构造函数后显示 LNK 2019 未解析外部符号的代码错误
- Dlib LNK2001未解析的外部符号USER_ERROR__consistent_build_configurati
- 矛盾的未解决的外部符号+未使用的库与VS2017和FFMPEG 4
- 链接器错误:切换到unicode生成给出:未解析的外部符号WinMain
- 错误 LNK2019:未解析的外部符号"外部"C"此错误是什么?
- 错误 : LNK2019: 未解析的外部符号"外部 "C"