-1

I am trying to create an overloaded operator for my class, my class contains a 2d array container. I want use the operator as follows: fooClass a; a[i][j] = 4; i don't want to use it like a[i, j], a(i, j) or call a function to input or output an element. Is is possible?

Chaining the call wont work since the first returns pointer to array, and the second should return an element in an array i.e. a float.

my class looks something like this:

class foo
{
    public:
    foo();
    ~foo();

    foo& operator=(const foo&rhs);
    foo& operator=(const foo&&rhs);
    foo& operator=(std::initializer_list<std::initializer_list<float>> il); 
    friend std::ostream& operator<<( std::ostream& os, const foo&rhs);
    std::array<float, 3>& operator[](const int & rhs); <<<<HERE<<<< What should it return?

    private:
    std::array<std::array<float, 3>, 3> matrix;
};


int main()
{
    foo a;
    a = {{1,2,3},{4,5,6},{7,8,9}};
    a[1][2] = 13;
    cout << a[1][2] << endl;


    return(0);
}

My question is, how to do this, and what should the function ..... operator[](const int & rhs); return?

FYI I am not using the array container directly because I am implementing other functions also I am doing the matrix column major.

topcat
  • 177
  • 3
  • 17

1 Answers1

1

Doesn't this work?

  std::array<float, 3>& operator[](const int & rhs) {
    return matrix[rhs];
  }
Evgeny
  • 1,072
  • 6
  • 6
  • Yes it works, but I do not understand it, could you explain? – topcat Jan 20 '20 at 06:55
  • 1
    You have a matrix as array of arrays. First []operation is realized by custom operator[] - it returns reference to one of arrays into matrix. Second [] operation is realized by std::array::operator[]. – Evgeny Jan 20 '20 at 07:43