重载二维数组下标"[][]"
问题来源:(待续)
解决办法:
(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 };
测试代码为:

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 }
输出结果为:

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,
(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 };
测试代码为:

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 }
!十分感谢以下博客的作者:
http://www.2cto.com/kf/201403/285924.html
A mind needs books like a sword needs a whetstone.
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· ASP.NET Core 模型验证消息的本地化新姿势
· 对象命名为何需要避免'-er'和'-or'后缀
· 开发的设计和重构,为开发效率服务
· 从零开始开发一个 MCP Server!
· Ai满嘴顺口溜,想考研?浪费我几个小时
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· .NET 原生驾驭 AI 新基建实战系列(一):向量数据库的应用与畅想