未解析的外部符号 - 模板类

Zzz*_*Zzz 2 c++ templates

可能重复:
C++模板,链接错误

我正在尝试实现选择排序,但我不断收到错误(打印在下面).在我看来,我的所有包含和模板都正确完成.有人可以向我解释这个错误的原因以及调试此类错误的一般方法.通常情况下会出现包含或模板问题,但偶尔会出现在我不知道错误的情况下.谢谢.

错误LNK2019:函数_main中引用的未解析的外部符号"public:void __thiscall Selection :: SelectionSort(int*const,int)"(?SelectionSort @?$ Selection @ H @@ QAEXQAHH @ Z)

TEST.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];
    }
}
Run Code Online (Sandbox Code Playgroud)

SelcectionSort.h

template<class ItemType>
class Selection
{
public:
    void SelectionSort(ItemType[], int);
private:
    int MinIndex(ItemType[], int, int);
    void Swap(ItemType& , ItemType&);
};
Run Code Online (Sandbox Code Playgroud)

SelectionSort.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;
}
Run Code Online (Sandbox Code Playgroud)

riw*_*alk 6

将内容移动SelectionSort.cppSelectionSort.h类声明的正下方.还要确保在整个.h文件的内容周围有一个标题保护.

问题来自C++如何实现模板.每当它看到一个与模板类(如Selection<int>)一起使用的新类型时,它就会重新创建整个类,替换ItemTypeint.

因此,它需要在编译时知道类的完整定义(及其方法).它不能只使用类定义和延迟链接,直到以后.