2010-06-06 3 views
0

이 벡터 템플릿 클래스 구현을 찾았지만 XCode에서는 컴파일되지 않습니다.템플릿 클래스 생성 오류

헤더 파일 :

// File: myvector.h 

#ifndef _myvector_h 
#define _myvector_h 

template <typename ElemType> 
class MyVector 
{ 
public: 
    MyVector(); 
~MyVector(); 
int size(); 
void add(ElemType s); 
ElemType getAt(int index); 

private: 
ElemType *arr; 
int numUsed, numAllocated; 
void doubleCapacity(); 
}; 

#include "myvector.cpp" 

#endif 

실행 파일 : 나는 그대로 컴파일하려고하면

// File: myvector.cpp 

#include <iostream> 
#include "myvector.h" 

template <typename ElemType> 
MyVector<ElemType>::MyVector() 
{ 
arr = new ElemType[2]; 
numAllocated = 2; 
numUsed = 0; 
} 

template <typename ElemType> 
MyVector<ElemType>::~MyVector() 
{ 
delete[] arr; 
} 

template <typename ElemType> 
int MyVector<ElemType>::size() 
{ 
return numUsed; 
} 

template <typename ElemType> 
ElemType MyVector<ElemType>::getAt(int index) 
{ 
if (index < 0 || index >= size()) { 
    std::cerr << "Out of Bounds"; 
    abort(); 
} 
return arr[index]; 
} 

template <typename ElemType> 
void MyVector<ElemType>::add(ElemType s) 
{ 
if (numUsed == numAllocated) 
    doubleCapacity(); 
arr[numUsed++] = s; 
} 

template <typename ElemType> 
void MyVector<ElemType>::doubleCapacity() 
{ 
ElemType *bigger = new ElemType[numAllocated*2]; 
for (int i = 0; i < numUsed; i++) 
    bigger[i] = arr[i]; 
delete[] arr; 
arr = bigger; 
numAllocated*= 2; 
} 

, 나는 다음과 같은 오류 얻을 :의 "재정의 'MyVector :: MyVector을() " 모든 멤버 함수 (.cpp 파일)에 대해 동일한 오류가 표시됩니다. "예상 생성자, 소멸자, 또는 형식 변환 '을 <'전에 :

는이 문제를 해결하기 위해, 나는 .cpp 파일에 '#INCLUDE"myvector.h "를'제거,하지만 지금은 새로운 오류 토큰". 모든 구성원에 대해서도 유사한 오류가 표시됩니다.

충분히 흥미롭게도 모든 .cpp 코드를 헤더 파일로 옮기면 잘 컴파일됩니다. 그렇다면 별도의 파일에 템플릿 클래스를 구현할 수 없습니까?

답변

0

템플릿을 헤더 파일에 배치하는 것이 좋습니다. 그렇게하면 동일한 인스턴스화 등의 여러 정의로 링커를 망칠 필요가 없습니다.

물론 순환 삽입이 있습니다. :)

0

첫째, 당신은 파일 간의 순환 참조를 생성

#include "myvector.cpp" 

있습니다. 그냥 제거하십시오.

다른 문제는 .cpp 파일 내에 템플릿 클래스를 정의한다는 것입니다. 템플릿 정의는 헤더 파일 내에서만 허용됩니다. 그 주위에는 방법이있을 수 있지만, g ++ (Xcode에서 사용)의 경우 쿠키가 무너지는 방식입니다.

+1

.cpp 파일 내에서 허용되지 않는 것은 아닙니다. 템플릿이 어떻게 작동하는지 (그리고'export' 키워드의 적절한 지원이 부족한) 고유 한 방식으로 컴파일과 링크를하면 문제가 있습니다. – Pieter

관련 문제