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

时间:2012-10-11 21:35:01

标签: c++ templates

  

可能重复:
  C++ template, linking error

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

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

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];
    }
}

SelcectionSort.h

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

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;
}

1 个答案:

答案 0 :(得分:6)

SelectionSort.cpp的内容移至SelectionSort.h,就在类声明的正下方。还要确保整个.h文件的内容都有一个标题保护。

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

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

相关问题