overloading operator []

A

Aff@n

hi,
i wold like to ask, why is it when overloading operator[] we send int
value is there any way around?.
e.g.
class abc
{
protected:
int *a;
private:
int operator[](int );
};

int abc::eek:perator[](int x)
{
int z;
z=a[x];
return z;
};
 
K

Kai-Uwe Bux

Aff@n said:
hi,
i wold like to ask, why is it when overloading operator[] we send int
value is there any way around?.
e.g.
class abc
{
protected:
int *a;
private:
int operator[](int );
};

int abc::eek:perator[](int x)
{
int z;
z=a[x];
return z;
};

In your case, operator[] takes an int argument because and only because you
defined it that way. You could as well do:

class abc
{
protected:
int *a;
private:
int operator[]( std::size_t );
};

int abc::eek:perator[]( std::size_t x)
{
int z;
z=a[x];
return z;
};


Best

Kai-Uwe Bux
 
J

Jim Langston

Aff@n said:
hi,
i wold like to ask, why is it when overloading operator[] we send int
value is there any way around?.
e.g.
class abc
{
protected:
int *a;
private:
int operator[](int );

here you are telling it to take an int value. You want it to take something
else, have it.

int operator[]( const std::string& );
int operator[]( float );
int operator[]( const MyClass& );
};

int abc::eek:perator[](int x)
{
int z;
z=a[x];
return z;
};

Of course, you'd want to do somethign meaningful with the parameter. In one
of my classes I am passing a std::string& which I am using to look up the
value in a map with std::string as the key.

Proxy operator[]( const std::string& Key )
{
return Proxy(*this, Key);
}

Of coure I'm not returning an int either, but my own class. Why I'm doing
this really has nothing to do with your question though, this is just to
show you that operator[] can accept and return anything.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,780
Messages
2,569,608
Members
45,241
Latest member
Lisa1997

Latest Threads

Top