重载二维数组下标"[][]"

问题来源:(待续)

解决办法:

(1) 可变长数组

对于可变的二维数组下标重载,在数组初始化时指定维数,之后可以像一般的二维数组进行赋值和取值操作. 当然,使用模板template来实现更好.

 1 class Array2d{
 2     private:
 3         int* a;
 4         int nrow;
 5         int ncol;
 6     public:
 7         Array2d(const int nrow_, const int ncol_)
 8         :nrow(nrow_), ncol(ncol_)
 9         {
10             a = new int[nrow * ncol];
11         }
12         Array2d(){}
13 
14         ~Array2d(){
15             delete[] a;
16         }
17         
18         int* operator[](const int idx) const {
19             return &a[idx * ncol]; 
20         }
21 
22         int operator()(const int x, const int y){
23             return a[x * ncol + y]; 
24         }
25 
26         Array2d& operator=(Array2d& aobj){
27             this->nrow = aobj.getNrow();
28             this->ncol = aobj.getNcol();
29             this->a = new int[nrow * ncol];
30             for(int i = 0; i < nrow; ++i ){
31                 for(int j = 0; j < ncol; ++j){
32                     this->a[i * ncol + j] = aobj[i][j];
33                 }
34             }
35         }
36         int getNrow(){ return nrow; }
37         int getNcol(){ return ncol; }
38         int* getA(){ return a; }
39 };
Array2d

测试代码为:

 1 int main() {
 2     Array2d a(3,4);
 3     int i,j;
 4     for(  i = 0;i < 3; ++i )
 5         for(  j = 0; j < 4; j ++ )
 6             a[i][j] = i * 4 + j;
 7     for(  i = 0;i < 3; ++i ) {
 8         for(  j = 0; j < 4; j ++ ) {
 9             cout << a(i,j) << ",";
10         }
11         cout << endl;
12     }
13     cout << "next" << endl;
14     Array2 b;     b = a;
15     for(  i = 0;i < 3; ++i ) {
16         for(  j = 0; j < 4; j ++ ) {
17             cout << b[i][j] << ",";
18         }
19         cout << endl;
20     }
21     return 0;
22 }
test_code

输出结果为:

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,
result

 

(2)固定长数组

据悉,固定维数的二维数组下标重载,一般在像3D图形方面经常涉及到一些平移转换矩阵时用到,这里以 4 * 4 的矩阵为例

1 struct Matrix4f
2 {
3     float m[4][4];
4 
5     float * const operator[](const int i)
6     {
7         return m[i];
8     }
9 };
Matrix4f

测试代码为:

1 int main(){
2     Matrix4f m;
3     m[0][0] = 1.0f;
4     m[1][1] = 9.9f;
5     cout << m[0][0] << endl;          // 1
6     cout << m[1][1] << endl;          // 9.9
7     return 0;        
8 }
test_code

 

 

!十分感谢以下博客的作者:

http://www.2cto.com/kf/201403/285924.html

posted @ 2015-09-23 19:37  _扬帆起航  阅读(580)  评论(0编辑  收藏  举报