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

Unresolved External Symbol -- Template Class

本文关键字:符号 外部      更新时间:2023-10-16

可能的重复项:
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

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

相关文章: