0

In various examples i saw that you can make different operators in a class for reading and for writing to a class array element. But when i try this example on Mingw and Borland it always calls the writing operator.


    class Point3
    {
        float coord[3];
    public:
        float   operator [] (int index) const; // For reading
        float & operator [] (int index);       // For writing
    };

    float Point3::operator [] (int index) const
    {
        printf("reading... \n") ;
        return 123.0*coord[index];
    }

    float & Point3::operator [] (int index)
    {
        printf("writing... \n") ;
        return coord[index];
    }



    int main(int argc, char* argv[]) 
    {
        Point3 xyz ;
        xyz[0] = 1.0 ;
        printf("%3.2f",xyz[0]) ;
        return 0 ;
    }



    output:

    writing...
    writing...
    1.00
archimedes
  • 89
  • 5

1 Answers1

1

If you want to use the const overload, you first have to create a const value:

printf("%3.2f", static_cast<const Point3 &>(xyz)[0]);
//              ^^^^^^^^^^^^^^^^^^^^^^^^^^^

There's a helper function for that in C++17:

printf("%3.2f", as_const(xyz)[0]);
//              ^^^^^^^^

In programming and computer science, "reading" and "writing" often not so much mutually exclusive, but rather "reading" is a subset of "writing": You either have read-only access to a resource, or you have read-and-write access. That's how you should think of those two overloads.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084