#include <iostream> #include <cstring> using namespace std; class Array2 { int **p; public: Array2(){}; Array2(int x,int y){ p=new int*[x]; for(int i=0;i<x;i++) p[i]=new int[y]; } int *operator[](int index){return p[index];}; int operator ()(int i,int j){ return p[i][j];}; }; 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; }
好吧,还是要老老实实建一个二维数组(之前写法太蛇皮了2333)
public: int * p=NULL; int *pp; int r,c; int mark=0; Array2 (int i,int j){ int* tmp; tmp=new int[i*j]; p=tmp; r=i; c=j; } Array2(){ p=NULL; } Array2& operator[](int i){ if(mark==0){ pp=p+i*c; mark=1;} else{ pp+=i; mark=0; } return *this; } friend ostream& operator<<(ostream& os,Array2 s){ os<<*(s.pp); return os; } void operator=(int n){ *(pp)=n; } void operator=(Array2& s){ p=s.p; r=s.r; c=s.c; } int& operator()(int i,int j){ return *(p+i*c+j); }