首页 > 解决方案 > 错误 C2995:已定义函数模板。未发现循环

问题描述

我已经引用了其他一些类似的问题,他们经常会指出循环性是问题所在。但我在代码中的任何地方都看不到这一点。

数组i.cpp:

#include "arrayi.h"

// Member function definitions for class Array

// Initialize static data member at file scope
template<typename T>
int Array<T>::arrayCount = 0;   // no objects yet

// Default constructor for class Array
template<typename T>
Array<T>::Array(int arraySize)
{
    ++arrayCount;             // count one more object
    size = arraySize;         // default size is 10
    ptr = new int[size];      // create space for array
    assert(ptr != 0);  // terminate if memory not allocated
    int i;
    for (i = 0; i < size; i++)
        ptr[i] = 0;            // initialize array
}

数组i.h:

#ifndef ARRAYI_H_
#define ARRAYI_H_

#include <iostream>
#include <cstdlib>
#include <cassert>
using namespace::std;




template<typename T> class Array;
template<typename T>
ostream &operator<< (ostream& output, const Array<T> &a);





template<typename T>
class Array
  {
    friend ostream &operator<< <>(ostream &output, const Array<T> &a);


  public:
    Array(int = 10);    //constructor
    Array(const Array &);   //copy constructor


  private:
      int *ptr; //ptr to first array element
      int size; //size of the array
      static int arrayCount;    // #of arrays instantiated
 };

#include "arrayi.t"

#endif

数组.t:

#ifndef ARRAYI_T_
#define ARRAYI_T_

#include <iostream>
#include <cstdlib>
#include <cassert>
using namespace::std;

// Default constructor for class Array
template<typename T>
Array<T>::Array(int arraySize)
{
cout << "calling the constructor \n";

}




// Overloaded output operator for class Array
template<typename T>
ostream &operator<<(ostream &output, const Array<T> &a)
{

  int i;
  output << "{ ";

  for (i = 0; i < a.size; i++)
    {
      output << a.ptr[i] << ' ';

      if ((i + 1) % 10 == 0)
        output << "}" << endl;
    }  //end for

  if (i % 10 != 0)
    output << "}" << endl;

  return output;   // enables cout << x << y;
}


#endif

我已经上下扫描了我的代码好几个小时了,所以任何帮助将不胜感激,在此先感谢!任何看起来凌乱或损坏的代码可能是因为这是来自正在进行的工作,但目前除了提到的错误之外没有任何错误。删除函数“Array::Array(int arraySize)”后,所有显示的内容都会编译。

标签: c++compiler-errorsheader-files

解决方案


arrayit.t 定义

Array<T>::Array(int arraySize)
{
cout << "calling the constructor \n";

}

arrayi.cpp 定义

template<typename T>
Array<T>::Array(int arraySize)
{
    ++arrayCount;             // count one more object
    size = arraySize;         // default size is 10
    ptr = new int[size];      // create space for array
    assert(ptr != 0);  // terminate if memory not allocated
    int i;
    for (i = 0; i < size; i++)
        ptr[i] = 0;            // initialize array
}

不允许使用相同参数的相同函数的两个定义。

解决方案:

选择一个是真正的构造函数。删除另一个。如果您选择 arrayi.cpp 中的实现,请确保它对需要它的翻译单元可见。这很可能意味着将其移至arrayi.t。

阅读模板静态变量,以便提前了解您遇到的另一个问题。


推荐阅读