为什么程序不起作用

Why programm does not work?

本文关键字:不起作用 程序 为什么      更新时间:2023-10-16

为数组创建了一个模板类。然后我创建了构造函数和析构函数,重载了输入和输出运算符。

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;
}

我该如何解决这个问题?

好吧,这是你的问题:

template< typename T> ostream& operator << (istream &in, const myArray<T> &el)

应该是

template< typename T> ostream& operator << (ostream &out, const myArray<T> &el)

复制粘贴错误...编辑:所以,我在写这个答案时看到Some programmer dude评论中说了这句话。对不起。

编辑2:删除它,因为它不是必需

template <typename T> class myArray;
template< typename T> ostream& operator <<(ostream &, const myArray <T> &);
template< typename T> istream& operator >> (istream &, const myArray<T> &);

然后是更多错误:

friend istream& operator >> <T>(istream &, const myArray &);

应该是:

friend istream& operator >> (istream &, const myArray &)
{
    [inlined code]
}

接下来:

mas = new int*[line];
for (int i = 0; i <line; i++)
    mas[i] = new int[column];

应该是

mas = new T*[line];
for (int i = 0; i <line; i++)
    mas[i] = new T[column];

然后结束

myArray<T>::myArray(int n, int m)
{

应该是:

myArray<T>::myArray(int n, int m)
    : line(n)
    , column(m)
{

等等等等,代码中有很多错误