在 C++ 中重新定义 template<class T>

Vin*_*ana 7 c++ templates header redefinition

我已经搜索并搜索了我的问题的解决方案,但我似乎找不到。我正在使用 Code::Blocks 并且我收到模板类的重新定义错误。

这是我的“vectorAux.h”文件:

#ifndef vectoraux_h
#define vectoraux_h

#include <vector>
#include <algorithm>
#include <iostream>

template <typename T>
void removeDup(std::vector<T> & v);

template <typename T>
unsigned seqVectSearch(const std::vector<T> & v, unsigned first,
               unsigned last, const T& target);

template <typename T>
void writeVector(const std::vector<T> & v);

#include "vectorAux.cpp"
#endif
Run Code Online (Sandbox Code Playgroud)

这是我的“vectorAux.cpp”文件:

#include "vectorAux.h"

#include <vector>
#include <algorithm>
#include <iostream>

template <typename T>
void removeDup(std::vector<T> & v)
{
    std::vector<int> vector1;
    unsigned i, last = v.size();

    for(int j = 0; j <= v.size(); j++)
    {
        std::cout << seqVectSearch(v, j, last, j);
        if(seqVectSearch(v, j, last, j) != v[i])
            vector1.push_back(seqVectSearch(v, j, last, j));
    }
}

template <typename T>
unsigned seqVectSearch(const std::vector<T> & v, unsigned first,
                       unsigned last, const T& target)
{
    unsigned i = first;
    while((v[i] != target) && (v[i] <= last))
    {
        if(v[i] == target)
            return i;
        i++;
    }
    return last;
}

template <typename T>
void writeVector(const std::vector<T> & v)
{
    unsigned i;
    unsigned n = v.size();

    for (i = 0; i < n; i++)
        std::cout << v[i] << ' ';
    std::cout << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

这个程序的最终文件是“vectorDriver.cpp”,但这个文件没有错误。这只是通过调用函数来运行程序:

#include "vectorAux.h"
#include <vector>
#include <iostream>

void fillVector(std::vector<int> & vect);

int main()
{
  using namespace std;

  vector<int> vect;

  fillVector(vect);
  cout << "Testing removeDup" << endl;
  cout << "Original vector is  ";
  writeVector(vect);

  removeDup(vect);
  cout << "Vector with duplicates removed is  ";
  writeVector(vect);
  cout << endl;
  writeVector(vect);

  return 0;
}

void fillVector(std::vector<int> & vect)
{
  int arr[] = {1,7,2,7,9,1,2,8,9};
  unsigned arrsize = sizeof(arr)/sizeof(int);

  vect = std::vector<int>(arr, arr+arrsize);
}
Run Code Online (Sandbox Code Playgroud)

我真的很感激所提供的任何帮助/建议!我已经环顾了一段时间,我发现的每个来源都说要保护头文件,但我已经这样做了,我的问题仍然存在。

joh*_*ohn 5

您在 vectorAux.h 中包含 vectorAux.cpp。我猜你也在单独编译 vectorAux.cpp 。所以你最终编译了 vectorAux.cpp 中的代码两次。

答案很简单,把vectorAux.cpp的代码移到vectorAux.h,把vectorAux.cpp删掉,不需要了。

模板代码几乎总是在头文件中。


Red*_*edX 2

简单的答案是:模板不应分为源文件和头文件。使用模板时将其全部保留在头文件中。