qq_32742637 于 2016.04.11 17:13 提问

#include
#include
using namespace std;
class Array
{
private:
int **arr;
int n,m;
public:
Array(int nn, int mm);
Array(const Array &stc);
~Array();
friend Array operator+(Array a1, Array a2);
friend ostream& operator<<(ostream &,Array &a);
friend istream& operator>>(istream &, Array &a);
Array operator=(Array a1);
};
Array::Array(int nn, int mm)
{
n = nn;
m = mm;
arr = new int [nn];
for (int i = 0; i < m; i++)
{
arr[i] = new int[mm];
}
}
Array::Array(const Array &stc)
{
m = stc.m;
n = stc.n;
arr = new int
[n];
for (int i = 0; i < m; i++)
{
arr[i] = new int[m];
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
arr[i][j] = stc.arr[i][j];
}
}
}
Array::~Array()
{
for (int i = 0; i < n; i++)
{
delete[]arr[i];
}
//delete[] arr; //加上这句会出错，为什么？？？？。不加就会正常运行
}
Array operator+(Array a1, Array a2)
{
Array a(a1.n, a1.m);
for (int i = 0; i < a1.n; i++)
{
for (int j = 0; j < a1.m; j++)
{
a.arr[i][j] = a1.arr[i][j] + a2.arr[i][j];
}
}
return a;
}
Array Array::operator=(Array a1)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
arr[i][j] = a1.arr[i][j];
}
}
return *this;
}
istream& operator>>(istream & input, Array &a)
{

``````for (int i = 0; i <a.n ; i++)
{
for (int j = 0; j < a.m; j++)
{
input >> a.arr[i][j];
}
}
return input;
``````

}
ostream& operator<<(ostream & output, Array &a)
{

``````for (int i = 0; i <a.n; i++)
{
for (int j = 0; j < a.m; j++)
{
cout.width(3);
output << a.arr[i][j];
}
output << endl;
}
return output;
``````

}
void main()
{
int n, m;
cin >> n >> m;
Array arr1(n, m), arr2(n, m), arr3(n, m);
cin >> arr1;
cin >> arr2;
arr3 = arr1 + arr2;
cout << arr1<<endl;
cout << arr2 << endl;
cout << arr3 << endl;
system("pause");

}

2个回答

lxffff1990   2016.04.11 17:34

qq_32742637 回复lxffff1990: 懂了。谢啦

qq_32742637 回复lxffff1990: 懂了。谢啦

lxffff1990   2016.04.11 17:33
qq_32742637 for (int i = 0; i < m; i++) { delete[]arr[i]; } delete[]arr; 改了一下还是不对，只有输入行和列相等的时候才不会出错