二维数组运算符重载

来源:互联网 发布:大数据技术相关书籍 编辑:程序博客网 时间:2024/06/06 20:37

二维数组运算符重载

这是Coursera一个公开课上的作业题


写一个类,可以满足输出为
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,

class Array2{public:    Array2(){        curcol = -1;        ptr = NULL;    }    Array2(int, int);    Array2(Array2 &a);    int* operator[](int);    int& operator[](int) const;    int& operator()(int a, int b);private:    int **ptr;    int size;    int curcol;    int col;    int row;};Array2::Array2(int a, int b){    ptr = new int*[a];    size = a*b;    for(int i=0;i<a;++i)        ptr[i] = new int[b];    col = a;    row = b;    curcol = -1;}Array2::Array2(Array2 &a){    if( !a.ptr ){        ptr = NULL;        size = 0;        return;    }    ptr = new int*[a.col];    for(int i=0;i<a.col;++i)        ptr[i] = new int[a.row];    memcpy(ptr, a.ptr, sizeof(int)*a.size);    size = a.size;}int* Array2::operator[](int i){    curcol = i;    return *(ptr+i);}int& Array2::operator[](int i) const{    return *(*(ptr+curcol)+i);}int& Array2::operator()(int a, int b){    return *(*(ptr+a)+b);}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;}

只是为了满足题目需求,所以没有扩展的很完全。
重载“[]“的时候纠结了很久,后来想起来C++里参数表相同,可以通过是否是const静态方法区分。

如果哪里写的有问题还请大家多多指教哈~~

0 0
原创粉丝点击