题目描述
写一个二维数组类 Array2,使得下面程序的输出结果是:
0,1,2,3,
4,5,6,7,
8,9,10,11,
next
0,1,2,3,
4,5,6,7,
8,9,10,11,
程序:
#include
#include
using namespace std;
class Array2 {
// 在这里输入你的代码
};
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;
}
输入
无
输出
0,1,2,3,
4,5,6,7,
8,9,10,11,
next
0,1,2,3,
4,5,6,7,
8,9,10,11,
样例输入 Copy
None
样例输出 Copy
0,1,2,3,
4,5,6,7,
8,9,10,11,
next
0,1,2,3,
4,5,6,7,
8,9,10,11,
#include <iostream>
#include <cstring>
using namespace std;
class Array2 {
// 在这里输入你的代码
private:
int** array;
int row;
int column;
public:
Array2()
{
row = 0;
column = 0;
array = NULL;
}
Array2(int row, int column) :row(row), column(column) {
array = new int* [row];
for (int idx = 0; idx < row; ++idx)
{
array[idx] = new int[column];
}
}
~Array2()
{
for (int idx = 0; idx < row; ++idx)
{
delete[] array[idx];
}
delete[] array;
}
int* operator [] (int idx)
{
return array[idx];
}
int& operator ()(int i, int j)
{
return*(*(array + i) + j);
}
Array2& operator = (const Array2& arr)
{
if (array != NULL)
{
for (int idx = 0; idx < arr.row; ++idx)
{
delete[] array[idx];
}
delete[] array;
}
else
{
row = arr.row;
column = arr.column;
array = new int* [arr.row];
for (int idx = 0; idx < arr.row; ++idx)
{
array[idx] = new int[arr.column];
}
for (int i = 0; i < row; ++i)
{
for (int j = 0; j < column; ++j)
{
*(*(array + i) + j) = *(*(arr.array + i) + j);
}
}
}
return *this;
}
};
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;
}