运算符[] []重载

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)

这只是一个简单的例子,你想要添加一堆边界检查和东西,但你明白了.

  • 可以使用析构函数.并且`Proxy :: operator []`应该返回`int&`而不仅仅是`int` (4认同)
  • @ abcdabcd987由于几个原因,这是不正确的.首先,`Proxy :: operator []`不会在此代码中返回引用(假设您的注释不是对Ryan Haining的回复).更重要的是,如果`arr`是const,则不能使用`operator []`.你必须定义一个const版本,当然你会让它返回`const Proxy`.然后`Proxy`本身会有const和非const方法.然后你的例子仍然无法编译,程序员会很高兴宇宙中的一切都很好.=) (4认同)

Lig*_*ica 19

表达式x[y][z]要求x[y]计算d支持的对象d[z].

这意味着x[y]应该是一个对象,其operator[]值为"代理对象",支持operator[].

这是链接它们的唯一方法.

或者,重载operator()以获取多个参数,以便您可以调用myObject(x,y).


Bo *_*son 17

对于二维数组,具体而言,您可能会使用单个operator []重载,它会返回指向每行第一个元素的指针.

然后,您可以使用内置索引运算符来访问行中的每个元素.

  • 在我看来,这是最实用,最有效的解决方案.不知道为什么它没有得到更多的选票 - 也许是因为它没有引人注目的代码. (4认同)

Joh*_*ohn 16

如果您在first []调用中返回某种代理类,则可以.但是,还有其他选项:您可以重载operator(),它可以接受任意数量的参数(function(3,3)).


Aja*_*jay 8

一种方法是使用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)

当然,你可能typedefpair<int,int>

  • 使用C++ 11和大括号初始化,这变得非常有吸引力.现在你可以写`nValue = theArray [{2,3}];` (6认同)

Nod*_*ode 5

您可以使用代理对象,如下所示:

#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)


Ere*_*evi 5

如果您不想说 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)