017 二维数组类

#include <iostream>
#include <cstring>
using namespace std;

class Array2 {
public:
    int x, y;
    int * p;
    Array2() {}
    Array2(int xx, int yy) :x(xx), y(yy),p(nullptr) {
        p = new int[xx*yy];
    }
    int * operator[] (int i) {
        return &p[i * y];
    }

    int& operator() (int i, int j) {
        return p[i * y+j];
    }

    Array2 & operator= (const Array2 & b) {
        x = b.x;
        y = b.y;
        p = new int[b.x * b.y];
        memcpy(p, b.p, x * y * sizeof(int));
        return *this;

    }

    ~Array2() {
        if (p != nullptr) {
            delete[] p;
            p = nullptr;
        }
        
    }
};

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;
}
posted @ 2022-02-20 17:23  icefield817  阅读(98)  评论(0编辑  收藏  举报