LIM*_*IMA 5 c++ arrays 2d operator-overloading operator-keyword
我有一个2D数组,我想定义一个函数,它返回用户使用运算符重载的索引值.换一种说法:
void MyMatrix::ReturnValue()
{
int row = 0, col = 0;
cout << "Return Value From the last Matrix" << endl;
cout << "----------------------------------" << endl;
cout << "Please Enter the index: [" << row << "][" << col << "] =" << ((*this).matrix)[row][col] << endl;
}
Run Code Online (Sandbox Code Playgroud)
该操作((*this).matrix)[row][col]应该返回一个int.我不知道如何建立operator [][].
或者,我可以连接几个调用operator [],但我没有成功,因为第一次调用该操作将返回int*,第二次将返回int,它强制构建另一个运算符,我不想去做.
我能做什么?谢谢,
您可以operator []为类定义自己的。一个简单的方法可以看下面的方式
#include <iostream>
#include <iomanip>
struct A
{
enum { Rows = 3, Cols = 4 };
int matrix[Rows][Cols];
int ( & operator []( size_t i ) )[Cols]
{
return matrix[i];
}
};
int main()
{
A a;
for ( size_t i = 0; i < a.Rows; i++ )
{
for ( size_t j = 0; j < a.Cols; j++ ) a[i][j] = a.Cols * i + j;
}
for ( size_t i = 0; i < a.Rows; i++ )
{
for ( size_t j = 0; j < a.Cols; j++ ) std::cout << std::setw( 2 ) << a[i][j] << ' ';
std::cout << std::endl;
}
}
Run Code Online (Sandbox Code Playgroud)
程序输出是
0 1 2 3
4 5 6 7
8 9 10 11
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3315 次 |
| 最近记录: |