• Advertisement
Sign in to follow this  

overloaded operator[]

This topic is 2321 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

the tutorial i am currently reading states the following


class IntList
{
private:
int m_anList[10];

public:
void SetItem(int nIndex, int nData) { m_anList[nIndex] = nData; }
int GetItem(int nIndex) { return m_anList[nIndex]; }
};


The subscript operator is one of the operators that must be overloaded as a member function[/quote]
Why "must" it be a member function? i dont see a problem with making it a friend and doing the following.


class IntList
{
private:
int m_anList[10];

public:
void SetItem(int nIndex, int nData) { m_anList[nIndex] = nData; }
int GetItem(int nIndex) { return m_anList[nIndex]; }
friend operator[]( IntList& this, int index );
};


IntList& operator[]( IntList& this, int nindex )
{
return m_anList[nIndex];
}


what does it mean it "must" be a member function? will this give a compiler error? or is it reffering to something else im missing? -thanks ( i would put in a compiler but the PC i'm using is not mine )

Share this post


Link to post
Share on other sites
Advertisement
To summarize, if [font="Courier New"]operator[] [/font]was allowed as a namespace-level function instead of a member function, usage would appear like [font="Courier New"]intList [] 3[/font] instead of [font="Courier New"]intList[3][/font].

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement