2 qq 32742637 qq_32742637 于 2016.04.11 17:13 提问

大神帮着看一下,为什么加上delete[]arr,这句就会显示错误,不加就没事
c++

#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
lxffff1990   2016.04.11 17:34
已采纳
qq_32742637
qq_32742637 回复lxffff1990: 懂了。谢啦
一年多之前 回复
qq_32742637
qq_32742637 回复lxffff1990: 懂了。谢啦
一年多之前 回复
lxffff1990
lxffff1990   2016.04.11 17:33
qq_32742637
qq_32742637 for (int i = 0; i < m; i++) { delete[]arr[i]; } delete[]arr; 改了一下还是不对,只有输入行和列相等的时候才不会出错
一年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!