이 벡터 템플릿 클래스 구현을 찾았지만 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 코드를 헤더 파일로 옮기면 잘 컴파일됩니다. 그렇다면 별도의 파일에 템플릿 클래스를 구현할 수 없습니까?
.cpp 파일 내에서 허용되지 않는 것은 아닙니다. 템플릿이 어떻게 작동하는지 (그리고'export' 키워드의 적절한 지원이 부족한) 고유 한 방식으로 컴파일과 링크를하면 문제가 있습니다. – Pieter