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;
}
上一篇:线上发生OOM


下一篇:Angular 如何为多个项目使用单一存储仓库