ice*_*opo 87 c++ operator-overloading
是否有可能使[]操作员重载两次?允许,像这样:( function[3][3]像在二维数组中).
如果有可能,我想看一些示例代码.
Set*_*gie 111
您可以重载operator[]以返回可以operator[]再次使用的对象以获得结果.
class ArrayOfArrays {
public:
ArrayOfArrays() {
_arrayofarrays = new int*[10];
for(int i = 0; i < 10; ++i)
_arrayofarrays[i] = new int[10];
}
class Proxy {
public:
Proxy(int* _array) : _array(_array) { }
int operator[](int index) {
return _array[index];
}
private:
int* _array;
};
Proxy operator[](int index) {
return Proxy(_arrayofarrays[index]);
}
private:
int** _arrayofarrays;
};
Run Code Online (Sandbox Code Playgroud)
然后你就可以使用它:
ArrayOfArrays aoa;
aoa[3][5];
Run Code Online (Sandbox Code Playgroud)
这只是一个简单的例子,你想要添加一堆边界检查和东西,但你明白了.
Lig*_*ica 19
表达式x[y][z]要求x[y]计算d支持的对象d[z].
这意味着x[y]应该是一个对象,其operator[]值为"代理对象",也支持operator[].
这是链接它们的唯一方法.
或者,重载operator()以获取多个参数,以便您可以调用myObject(x,y).
Bo *_*son 17
对于二维数组,具体而言,您可能会使用单个operator []重载,它会返回指向每行第一个元素的指针.
然后,您可以使用内置索引运算符来访问行中的每个元素.
一种方法是使用std::pair<int,int>:
class Array2D
{
int** m_p2dArray;
public:
int operator[](const std::pair<int,int>& Index)
{
return m_p2dArray[Index.first][Index.second];
}
};
int main()
{
Array2D theArray;
pair<int, int> theIndex(2,3);
int nValue;
nValue = theArray[theIndex];
}
Run Code Online (Sandbox Code Playgroud)
当然,你可能typedef是pair<int,int>
您可以使用代理对象,如下所示:
#include <iostream>
struct Object
{
struct Proxy
{
Object *mObj;
int mI;
Proxy(Object *obj, int i)
: mObj(obj), mI(i)
{
}
int operator[](int j)
{
return mI * j;
}
};
Proxy operator[](int i)
{
return Proxy(this, i);
}
};
int main()
{
Object o;
std::cout << o[2][3] << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
如果您不想说 a[x][y],而是想说 a[{x,y}],则可以这样做:
struct Coordinate { int x, y; }
class Matrix {
int** data;
operator[](Coordinate c) {
return data[c.y][c.x];
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
48173 次 |
| 最近记录: |