c++ - C++ 错误 : redefinition of class constructor using templates

标签 c++ list templates

有人知道我该如何解决这些错误吗? 我已经看了一段时间了,只是不知道该怎么做。

错误:

indexList.cpp:18: error: redefinition of `indexList<T>::indexList()'
indexList.cpp:18: error: `indexList<T>::indexList()' previously declared here
indexList.cpp:30: error: redefinition of `bool indexList<T>::append(T)'
indexList.cpp:30: error: `bool indexList<T>::append(T)' previously declared here

cpp文件:

//
//
//
//
//
//
#include "indexList.h"
#include <iostream>
using namespace std;

//constuctor
//Descriptions: Initializes numberOfElement to 0
//              Initializes maxSize to 100
//Parameters:   none
//Return:       none
template <class T>
indexList<T>::indexList()
{
  numberOfElements = 0;
  maxSize = 100;
}


//Name: append
//Purpose: Adds element to the end of the list. If array is full, returns false
//Paramters: value - thing to append
//Return: true if append succeeds, false otherwise
template <class T>
bool indexList<T>::append(T value)
{
  if (maxSize > numberOfElements)
    {
      list[numberOfElements] = value;
      numberOfElements ++;
      return true;
    }
  else
    return false;
}

我没有把所有的cpp文件都放上去,因为其余的错误和上面的差不多,而且很长

标题:

#include <iostream>
using namespace std;


#ifndef INDEXLIST_H
#define INDEXLIST_H

template <class T>
class indexList
{
 public:
 indexList();

 bool append(T value);

 bool insert(int indx, T value);

 bool replace(int indx, T newValue);

 bool retrieve(int indx, T &value) const;

 bool remove(int indx);

 void sort();

 int search(T value) const;

private:
 T list[100];
 int numberOfElements;
 int maxSize;
};


template <class T>
ostream &operator<<(ostream &outStream, const indexList<T> &lst);

#include "indexList.cpp"

#endif

我确实放了整个标题

最佳答案

你的两个文件中的每一个都试图包含另一个,这可能会导致预处理器输出一些重复的代码。

从文件 indexList.cpp 中取出 #include "indexList.h"

此外,您的构建过程不应尝试将 indexList.cpp 编译成目标文件。

另一种安排方式是将您当前在 indexList.cpp 中的所有内容放在 indexList.h 的末尾附近,这样就不会有indexList.cpp 文件。

关于c++ - C++ 错误 : redefinition of class constructor using templates,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22623581/

相关文章:

c++ - 如果用作模板参数的类型在需要完整类型的上下文中内部使用,则何时必须完整?

c++ - 为什么在推导类型时去除模板参数的限定符?

c++ - C++ 中 this* 的类型

c++ - LNK1104 无法打开文件 'legacy_stdio_definitions.lib'

c# - 如何将 WorkItemCollection 转换为列表

python - 在 Python 中,如何在保留词序的同时从两个列表中找到常用词?

c++ - 安装 socket.io C++

c++ - VS2005 中损坏的 std::map 可视化工具

python - 引用列表项作为排序 for 循环中的键

C++ 函数与带有整数参数的模板?