我发现此矢量模板类实现,但它不能在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 2010-06-06 15:38:19