overloading operator []

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Aff@n

    #1

    overloading operator []

    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

    #2
    Re: overloading operator []

    Aff@n wrote:
    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

    Comment

    • David Harmon

      #3
      Re: overloading operator []

      >Aff@n wrote:
      >
      >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::s tring, int>.
      Its operator[] takes std::string for an argument.

      Comment

      • Jim Langston

        #4
        Re: overloading operator []


        "Aff@n" <affanyasin@gma il.comwrote in message
        news:1156748783 .465566.191880@ i3g2000cwc.goog legroups.com...
        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::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.


        Comment

        Working...