为什么programm不起作用?

时间:2017-03-19 09:29:03

标签: c++ arrays class templates

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

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

我该如何解决这个问题?

1 个答案:

答案 0 :(得分: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)
{

等等。代码中只有所以许多错误。