其他分享
首页 > 其他分享> > 017 二维数组类

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;
}

标签:return,int,Array2,xx,++,二维,数组,017,operator
来源: https://www.cnblogs.com/icefield817/p/15915929.html