Connecting Tech Pros Worldwide Forums | Help | Site Map

overloading operator []

Aff@n
Guest
 
Posts: n/a
#1: Aug 28 '06
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::operator[](int x)
{
int z;
z=a[x];
return z;
};


Kai-Uwe Bux
Guest
 
Posts: n/a
#2: Aug 28 '06

re: overloading operator []


Aff@n wrote:
Quote:
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::operator[](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::operator[]( std::size_t x)
{
int z;
z=a[x];
return z;
};


Best

Kai-Uwe Bux
David Harmon
Guest
 
Posts: n/a
#3: Aug 28 '06

re: overloading operator []


>Aff@n wrote:
Quote:
>
Quote:
>hi,
>i wold like to ask, why is it when overloading operator[] we send int
>value is there any way around?.
Sure there is. Consider std::map<std::string, int>.
Its operator[] takes std::string for an argument.

Jim Langston
Guest
 
Posts: n/a
#4: Aug 29 '06

re: overloading operator []



"Aff@n" <affanyasin@gmail.comwrote in message
news:1156748783.465566.191880@i3g2000cwc.googlegro ups.com...
Quote:
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& );
Quote:
};
>
int abc::operator[](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.


Closed Thread