4

重複の可能性:
C ++テンプレート、リンクエラー

選択ソートを実装しようとしていますが、エラーが発生し続けます(以下に印刷)。私のインクルードとテンプレートはすべて正しく行われているように思えます。誰かがこのエラーの理由とこのタイプのエラーをデバッグするための一般的なアプローチを私に説明できますか?通常、インクルードまたはテンプレートの問題がある場合に発生するようですが、何が問題なのかわからない状況で発生する場合があります。ありがとう。

エラー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;
}
4

1 に答える 1

8

の内容を、クラス宣言のすぐ下のに移動しSelectionSort.cppますSelectionSort.h.hまた、ファイル全体の内容の周りにヘッダーガードがあることを確認してください。

問題は、C++がテンプレートを実装する方法に起因します。テンプレートクラス(など)で使用される新しい型を検出するたびに、Selection<int>クラス全体が再作成され、。に置き換えItemTypeられintます。

このため、コンパイル時にクラスの完全な定義(およびそのメソッド)を知る必要があります。クラス定義を使用して、リンクを後でまで遅らせることはできません。

于 2012-10-11T21:37:10.387 に答える