2012-10-11 4 views
1

가능한 중복 :
C++ template, linking error되지 않은 외부 기호 - 템플릿 클래스

내가 선택 정렬을 구현하기 위해 시도하고 있지만 (아래 인쇄) 오류가 계속. 내 모든 포함 및 템플릿이 올바르게 수행되었다고 생각됩니다. 누군가이 오류에 대한 이유와이 유형의 오류를 디버깅하는 일반적인 방법을 설명 할 수 있습니까? 일반적으로 포함 또는 템플리트 문제가있을 때 발생하는 것으로 보이지만 때로는 무엇이 잘못되었는지를 모르는 상황에서 발생합니다. 감사.

오류 LNK2019 : 확인되지 않은 외부 기호 "공개 : 무효 __thiscall 선택 : 선택 정렬 (INT * const를, INT)"기능에서 참조 (? 선택 정렬 @ $ 선택 @ 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; 
} 
+0

@ DavidRodríguez-dribeas 방금 – PiotrNycz

답변

5

SelectionSort.cpp의 내용을 클래스 선언 바로 아래 SelectionSort.h으로 옮기십시오. 또한 전체 .h 파일의 내용을 헤더 가드가 있는지 확인하십시오.

문제는 C++에서 템플릿을 구현하는 방법에서 비롯됩니다. 템플릿 클래스 (예 : Selection<int>)와 함께 사용되는 새로운 유형이 표시 될 때마다 ItemTypeint으로 바꾸고 전체 클래스를 다시 만듭니다.

이런 이유로 컴파일 타임에 클래스의 전체 정의 (메소드와 함께)를 알아야합니다. 클래스 정의를 사용하고 나중에 연결할 때까지 연결을 지연시킬 수는 없습니다.

+0

감사합니다. 내 코드를 선언 및 구현 파일로 분리하는 동안 템플릿을 사용했습니다. 내가 그 프로젝트들을 돌아볼 때 나는 차이점을 발견 할 수 없다. 이전 프로젝트를 컴파일하게 만들었을 수도 있습니다. – Zzz

+0

나는 그들이 내가 컴파일하도록 한 것을 기억했다. 나는 include guards를 추가했고 또한 .cpp 구현 파일을 테스트 드라이버에 포함시켰다. 컴파일이 어떻게 바뀌어 모든 것을 작동 시키나요? – Zzz

+0

@Azzi, 결론은 컴파일러가'test.cpp' 파일을 컴파일하는 동안 템플릿 클래스의 전체 구현을 볼 수 있어야한다는 것입니다. 컴파일러가 완전한 구현 세부 사항에 액세스 할 수 있기 때문에 CPP 파일을 포함하지만 항상 가치있는 것보다 더 혼란 스럽습니다. – riwalk