Archived

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

Robbo

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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
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?

If you want syntactic sugar, use Perl or something. In C++, it very often leads to bad, bad, bad code.


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

Share this post


Link to post
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 this post


Link to post
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 this post


Link to post
Share on other sites
Arild Fines    968
Any user defined operator needs at least one argument of an UDT.



Faith. n. Belief without evidence in what is told by one who speaks without knowledge, of things without parallel. -- Ambrose Bierce

Share this post


Link to post
Share on other sites