C ++重载[] []列表

Ovi*_*scu 5 c++ list operator-overloading

class Matrix和一个成员在一起std::list<Element> listMatrix;Element是一个有3 int名成员的班级line, column, value。我通过保存行,列和相应元素的值在列表中保存不为0的矩阵元素。我想超载,operator [][]所以我可以做类似的事情Matrix a; a[2][3] = 5;。我知道你不能overload [][]直接。

YSC*_*YSC 9

做重载Element& operator()(int, int)(和const变体),以便您可以编写

matrix(2, 3) = 5;
Run Code Online (Sandbox Code Playgroud)

如果绝对需要[2][3]语法,则需要定义一个代理类,以便matrix[2]返回一个代理值并proxy[3]返回所需的引用。但这带来很多问题。基本思想是:

class naive_matrix_2x2
{
    int data[4];

    struct proxy
    {
          naive_matrix_2x2& matrix;
          int x;
          int& operator[](int y) { return matrix.data[x*2+y]; }
    };
public:
    proxy operator[](int x) { return {*this, x}; }
};
Run Code Online (Sandbox Code Playgroud)

完整演示:https : //coliru.stacked-crooked.com/a/fd053610e56692f6

  • 您不妨给代理起一个真实的名字-类class是我命名的方式。 (2认同)