Jump to content
  • Advertisement

Archived

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

WickedMystic

Operator[ ]

This topic is 6918 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Heya, say I have this class: class matrix { public: float value[16]; matrix() { for(int j = 0; j < 16; j++) value[j] = 0.0f; } }; I would like to define an operator[] that allows me to do stuff like this: matrix M; M[0] = 0; M[1] = 1; etc... But I have no idea how to actually do this. Is it even possible? Thanks WickedMystic Edited by - WickedMystic on 5/9/00 5:04:13 PM Edited by - WickedMystic on 5/9/00 5:10:25 PM

Share this post


Link to post
Share on other sites
Advertisement
Guest Anonymous Poster
The first operator[] is for read, the second is for read/write.

class CMatrix
{
public :
float operator[](unsigned int iElement) const { return m_afElements[iElement]; }

float& operator[](unsigned int iElement) { return m_afElements[iElement]; }

private :
float m_afElements[16];
};

Share this post


Link to post
Share on other sites
Hate to tell you this, but i don't think it can be done with that type of symbol.
M[] is used for arrays, such as you had made Matrix M[20]; so I think you would have to do something different.

You could make a function :
Matrix::setcell(int cell, float toset)
{
value[cell]=toset;
}

I think that should work... I might be wrong about not being able to do it your way, but I really don't think it would work.


Drakonite

--Don't quote me on that, unless I'm right.

Edited by - Drakonite on May 9, 2000 6:19:17 PM

Share this post


Link to post
Share on other sites
So you want to do something like this:

class Array {
char A[256];
public:
char operator[](int index);
};

char Array::operator[](int index) {
return A[index];
}

Share this post


Link to post
Share on other sites
Oh I see what you want it to do now . You''ll have to pass it back as a reference. Code below...

class CArray {
int Array[256];
public:
CArray();
int& operator[](int index);
};

CArray::CArray()
{
for(int x = 0; x < 256; x++)
Array[x] = 0;
}

int& CArray::operator[](int index)
{
return Array[index];
}

That will do what you want it to.

Share this post


Link to post
Share on other sites
You might want to make the const version of operator[] return a const reference.

as in

const float& operator[](unsigned int index) const;

Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!