• ### Announcements

#### Archived

This topic is now archived and is closed to further replies.

# How do I overload [] operator such that......

## Recommended Posts

Robbo    122
Hi, I''m writing a generic matrix implementation for an artificial neural network. I want to overload the subscript operator [], such that I can write: Matrix [j] = Value; or Value = Matrix [i][j]; I know I can overload [], but how does one go about overloading [][] or even [][][]!??? Thanks for any help you can give.

##### Share on other sites
civguy    308
You make that operator[] return a row (or column) to that matrix. That row is also an object, which has overloaded []. Then the second [] will access the row''s overloaded [].

I think it goes like this:

matrix[n][m] == (matrix.operator[](n)).operator[](m)

So the matrix.operator[](n) must return an object for which [] is overloaded.. Eh, I don''t think I''m going to say it third time

##### Share on other sites
Robbo    122

Oh - thanks mate - I think what I really wanted was the MTL - so much easier to use this than have to write my own.

Thanks a lot for your help.

##### Share on other sites
Evil Bill    126
Or use operator():

  float Matrix::operator() (int nRow, int nCol){   return m_fMat[nRow][nCol];}Matrix m;float f;f = m(1,2);

HTH, Steve

Steve
DirectX Programmer
Soon to be the new Bill Gates

##### Share on other sites
Sneftel    1788
Using programming tricks to get a nice looking [][] operator is the height of stupid. Is the extra inefficiency and complexity introduced really worth not using the () operator?

Don''t listen to me. I''ve had too much coffee.

##### Share on other sites
Brobanx    136
You could just overload [] in the matrix class, and then overload the comma operator in some helper class to get Matrix[2,3,4]. Heh, finally a reason to use operator comma.

##### Share on other sites
Oluseyi    2103
quote:
Original post by Brobanx
You could just overload [] in the matrix class, and then overload the comma operator in some helper class to get Matrix[2,3,4]. Heh, finally a reason to use operator comma.

Pointless. Inconsistent. Violates intentionality (what does that syntax convey to the reader of the code, uninformed of your overload but familiar with C++?)

Just use operator (). It''s quick, efficient and conveys intent quite well (function object-like syntax).

##### Share on other sites
petewood    819
can you overload operator, for ints?

if you can''t... do as the ints do.

##### Share on other sites
daerid    354
operator,() must have at least one argument of a user-defined type.