有人知道我该如何解决这些错误吗? 我已经看了一段时间了,只是不知道该怎么做。
错误:
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/