【发布时间】:2019-02-21 22:41:01
【问题描述】:
我已经引用了其他一些类似的问题,他们通常会指出循环性是问题所在。但我在代码中的任何地方都看不到这一点。
arrayi.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
}
arrayi.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
arrayi.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)”后,所有显示的内容都会编译。
【问题讨论】:
-
通常不应将模板的一部分放入 CPP 文件 (Explanation)。
-
将
using namespace std;放在标题中是不受欢迎的,因为它会将您的标题变成潜在的诱杀装置。如果文件包含您的标头,它现在使用命名空间std,如果您不期望它,可能会导致难以理解的错误。
标签: c++ compiler-errors header-files