#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");
}
二維數組創建錯誤
http://blog.sina.com.cn/s/blog_4e7ae8ca0100zqq6.html