C++ 创建模板类时出错

C++ 创建模板类时出错,c++,templates,C++,Templates,我找到了这个向量模板类实现,但它没有在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); priv

我找到了这个向量模板类实现,但它没有在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
//文件:myvector.h
#ifndef myvector h
#定义_myvector_h
模板
类MyVector
{
公众:
MyVector();
~MyVector();
int size();
无效添加(元素类型s);
ElemType getAt(int索引);
私人:
元素类型*arr;
内翻,内翻;
无效容量();
};
#包括“myvector.cpp”
#恩迪夫
实施文件:

// 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.cpp
#包括
#包括“myvector.h”
模板
MyVector::MyVector()
{   
arr=新的元素类型[2];
numlocated=2;
numUsed=0;
}
模板
MyVector::~MyVector()
{
删除[]arr;
}
模板
int MyVector::size()
{
回眸;
}
模板
ElemType MyVector::getAt(int索引)
{
如果(索引<0 | |索引>=size()){
首先,你有

 #include "myvector.cpp"
这会在文件之间创建一个循环引用。只要去掉它就行了


另一个问题是,您正在.cpp文件中定义模板类。模板定义只允许在头文件中进行。除了g++(XCode使用的)之外,可能还有其他解决方法这就是cookie崩溃的原因。

将模板放在头文件中始终是一个好主意。这样,您就不会因为同一实例化的多个定义之类的内容而弄乱链接器

当然还有循环包含:)。

这并不是说在.cpp文件中不允许使用它们。如果使用这种方式编译和链接,模板的工作方式会出现固有的问题(并且缺少对
导出
关键字的适当支持)。