【问题标题】:Error in creating template class创建模板类时出错
【发布时间】:2010-06-06 15:25:33
【问题描述】:

我找到了这个向量模板类的实现,但它不能在 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 代码移到头文件中,它编译得很好。这是否意味着我不能在单独的文件中实现模板类?

【问题讨论】:

    标签: c++ templates


    【解决方案1】:

    将模板放在头文件中总是一个好主意。这样一来,您就不会因为相同实例的多个定义等而弄乱链接器。

    当然还有循环包含:)。

    【讨论】:

      【解决方案2】:

      首先,你有

       #include "myvector.cpp"
      

      在文件之间创建循环引用。摆脱它。

      另一个问题是您在 .cpp 文件中定义模板类。模板定义只允许在头文件中。可能有办法解决这个问题,但对于 g++(XCode 使用),这就是 cookie 崩溃的方式。

      【讨论】:

      • 并不是说它们在 .cpp 文件中不被允许。如果以模板工作方式固有的方式完成编译和链接,那么编译和链接就会出现问题(并且缺乏对 export 关键字的体面支持)。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-16
      • 1970-01-01
      • 2021-07-06
      • 1970-01-01
      • 1970-01-01
      • 2022-08-22
      相关资源
      最近更新 更多