#include <iostream>
#include <cstring>
using namespace std;
class Array2
{
public:
Array2(int m_, int n_) : m(m_), n(n_)
{
arr = new int *[m_];
for (int i = 0; i < m_; ++i)
arr[i] = new int[n_];
}
Array2() : m(0), n(0)
{
arr = NULL;
}
Array2 &operator=(const Array2 &a)
{
if (this == &a)
return *this;
m = a.m;
n = a.n;
if (arr)
{
for (int i = 0; i < m; ++i)
delete[] arr[i];
delete[] arr;
}
if (a.arr)
{
arr = new int *[m];
for (int i = 0; i < m; ++i)
arr[i] = new int[n];
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
arr[i][j] = a.arr[i][j];
}
else
arr = NULL;
return *this;
}
~Array2()
{
if (arr)
{
for (int i = 0; i < m; ++i)
delete[] arr[i];
delete[] arr;
arr = NULL;
}
}
int *operator[](int m)
{
return arr[m];
}
int &operator()(int i, int j)
{
return arr[i][j];
}
int **arr;
int m, n;
};
int main()
{
Array2 a(3, 4);
int i, j;
for (i = 0; i < 3; ++i)
for (j = 0; j < 4; j++)
a[i][j] = i * 4 + j;
for (i = 0; i < 3; ++i)
{
for (j = 0; j < 4; j++)
{
cout << a(i, j) << ",";
}
cout << endl;
}
cout << "next" << endl;
Array2 b;
b = a;
for (i = 0; i < 3; ++i)
{
for (j = 0; j < 4; j++)
{
cout << b[i][j] << ",";
}
cout << endl;
}
return 0;
}
- 主要考察”()”和”[]”运算符的重载,同时考察了二维数组指针的动态申请和拷贝等操作
- 关注“()”和“[]”运算符的重载
- 注意二维数组的申请,申请第二维的时候是for(i=0; i < m; ++i),不是for(i=0; i < n; ++i)