Sign in to follow this  
nuclear123

overloaded operator[]

Recommended Posts

the tutorial i am currently reading states the following

[code]
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]; }
};
[/code]

[quote]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.

[code]
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];
}
[/code]

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
[url="http://stackoverflow.com/questions/4421706/operator-overloading/4421729#4421729"]Googling found this.[/url]


I was going to put "If SiCrane doesn't ninja me first" at the beginning of this post, but as soon as I clicked reply his post already existed.

Share this post


Link to post
Share on other sites
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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this