Operator[][] overload

2018-12-31 14:08发布

Is it possible to overload [] operator twice? To allow, something like this: function[3][3](like in a two dimensional array).

If it is possible, I would like to see some example code.

17条回答
只若初见
2楼-- · 2018-12-31 14:56

Using C++11 and the Standard Library you can make a very nice two-dimensional array in a single line of code:

std::array<std::array<int, columnCount>, rowCount> myMatrix {0};

std::array<std::array<std::string, columnCount>, rowCount> myStringMatrix;

std::array<std::array<Widget, columnCount>, rowCount> myWidgetMatrix;

By deciding the inner matrix represents rows, you access the matrix with an myMatrix[y][x] syntax:

myMatrix[0][0] = 1;
myMatrix[0][3] = 2;
myMatrix[3][4] = 3;

std::cout << myMatrix[3][4]; // outputs 3

myStringMatrix[2][4] = "foo";
myWidgetMatrix[1][5].doTheStuff();

And you can use ranged-for for output:

for (const auto &row : myMatrix) {
  for (const auto &elem : row) {
    std::cout << elem << " ";
  }
  std::cout << std::endl;
}

(Deciding the inner array represents columns would allow for an foo[x][y] syntax but you'd need to use clumsier for(;;) loops to display output.)

查看更多
与君花间醉酒
3楼-- · 2018-12-31 14:57

My 5 cents.

I intuitively knew I need to do lots of boilerplate code.

This is why, instead of operator [], I did overloaded operator (int, int). Then in final result, instead of m[1][2], I did m(1,2)

I know it is DIFFERENT thing, but is still very intuitive and looks like mathematical script.

查看更多
栀子花@的思念
4楼-- · 2018-12-31 15:03

Have you got any idea about what function, function[x] and function[x][y] mean?

First take a look at where function is defined. Maybe there is some declaration or definition like

SomeClass function;

(Because you said that it's operator overload, I think you won't be interested at array like SomeClass function[16][32];)

So function is an instance of type SomeClass. Then look up declaration of SomeClass for the return type of operator[] overload, just like

ReturnType operator[](ParamType);

Then function[x] will have the type ReturnType. Again look up ReturnType for the operator[] overload. If there is such a method, you could then use the expression function[x][y].

Note, unlike function(x, y), function[x][y] is 2 separated calls. Neither compiler nor runtime garantees the atomicity. Another similar example is, libc says printf is atomic while successively calls to the overloaded operator<< in output stream are not. A statement like

std::cout << "hello" << std::endl;

might have problem in multi-thread application, but something like

printf("%s%s", "hello", "\n");

is OK.

In conclusion, though C++ is able to offer such a syntactic sugar for you, it is not the recommended way to program.

查看更多
人气声优
5楼-- · 2018-12-31 15:04
#include<iostream>

using namespace std;

class Array 
{
     private: int *p;
     public:
          int length;
          Array(int size = 0): length(size)
          {
                p=new int(length);
          }
          int& operator [](const int k)
          {
               return p[k];
          }
};
class Matrix
{
      private: Array *p;
      public: 
            int r,c;
            Matrix(int i=0, int j=0):r(i), c(j)
            {
                 p= new Array[r];
            }
            Array& operator [](const int& i)
            {
                 return p[i];
            }
};

/*Driver program*/
int main()
{
    Matrix M1(3,3); /*for checking purpose*/
    M1[2][2]=5;
}
查看更多
临风纵饮
6楼-- · 2018-12-31 15:06

One approach is using 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];
}

Of course, you may typedef the pair<int,int>

查看更多
深知你不懂我心
7楼-- · 2018-12-31 15:08

If, instead of saying a[x][y], you would like to say a[{x,y}], you can do like this:

struct Coordinate {  int x, y; }

class Matrix {
    int** data;
    operator[](Coordinate c) {
        return data[c.y][c.x];
    }
}
查看更多
登录 后发表回答