1018: *第四周程序填空题3,自定义数组

题目描述
写一个二维数组类 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;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值