c++ - 错误 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)”后,所有显示的内容都会编译。
解决方案
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。
阅读模板静态变量,以便提前了解您遇到的另一个问题。
推荐阅读
- c# - 将特定符号转换为 lat
- django - Django,同时删除一个对象并创建一个新对象(在新模型中)
- amazon-web-services - 无法 RDP 到 Amazon EC2 实例(Windows 服务器)
- node.js - 如何在我的 Express 生成器应用程序运行之前从 db 获取数据?
- java - 如何在Spring的循环中设置按钮值
- python - Python - 为多维列表赋值
- ruby-on-rails - 部署到 Heroku 的问题:缺少 'secret_key_base' 和未初始化的常量 Posts (NameError)
- amazon-web-services - 如何在没有 CLI 或脚本的情况下每 10 分钟删除对象中的 S3 文件?
- javascript - 输入值看不到完整,为什么?
- java - 为什么我会得到 java.lang.NullPointerException