【发布时间】:2017-03-19 09:29:02
【问题描述】:
为数组创建了一个模板类。然后我创建了构造函数和析构函数,重载了输入和输出操作符。
using std::istream;
using std::ostream;
template <typename T> class myArray;
template< typename T> ostream& operator <<(ostream &, const myArray <T> &);
template< typename T> istream& operator >> (istream &, const myArray<T> &);
template <typename T> class myArray
{
private:
T**mas;
int line,
column;
friend istream& operator >> <T>(istream &, const myArray &);
friend ostream& operator << <T>(ostream &, const myArray &);
public:
myArray() : mas (0), line ( 0) column (0) {}
myArray(int n, int m);
myArray(const myArray &masToCopy);
~myArray()
{
for (int i = 0; i<line; i++)
{
delete[](mas[i]);
}
delete[](mas);
}
};
template <typename T> myArray <T>::myArray(int n ,int m )
{
mas = new T*[n];
for (int i = 0; i < n; i++)
{
mas[i] = new T[m];
}
}
template <typename T> myArray <T>:: myArray(const myArray &masToCopy)
{
line = masToCopy.line;
column = masToCopy.column;
mas = new T*[line];
for (int i = 0; i <line; i++)
mas[i] = new T[column];
for (int i = 0; i<line; i++)
for (int j = 0; j < column; j++)
mas[i][j] = masToCopy.mas[i][j];
}
template< typename T> istream& operator >> (istream &in, const myArray<T> &el)
{
for (int i = 0; i < el.line; i++)
{
for (int j = 0; j < el.column; j++)
{
in >> el.mas[i][j];
}
}
return in;
}
template< typename T> ostream& operator << (ostream &out, const myArray<T> &el)
{
for (int i = 0; i < el.line; i++)
{
cout << "\n";
for (int j = 0; j < el.column; j++)
{
out << el.mas[i][j];
cout << " ";
}
}
return out;
}
当我尝试使用我的类时,程序不允许输入数组,然后不显示它。相反,它立即写“要继续,请按任意键”
using std:: cin;
using std::cout;
int main()
{
myArray<int> intArray1(2,2);
cin >> intArray1;
cout << intArray1;
return 0;
}
我该如何解决这个问题?
【问题讨论】:
-
您可以为我们节省一些时间并告诉我们它找不到哪个符号。
-
与您的问题无关,但是当您在构造函数中分配内存时,您不应该使用
T而不是int作为类型吗? IE。mas[i] = new T[m];而不是mas[i] = new int[m]? -
@nwp 我添加了截图
-
至于您的问题,您似乎犯了复制粘贴错误。输入和输出运算符都将
istream作为其第一个参数。您的输出运算符在其他方面也存在缺陷,使用cout而不是所谓的输出流。顺便说一句,该函数不应该通过编译器到达链接器。 -
@Ap31 不是真的。模板类可能会发生这种情况。
标签: c++ arrays class templates