Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading the subscript operator "[ ]" in the l-value and r-value cases

I have overloaded [] operator in my class Interval to return minutes or seconds.

But I am not sure how to assign values to minutes or second using [] operator.

For example : I can use this statement

cout << a[1] << "min and " << a[0] << "sec" << endl;

but I want to overload [] operator, so that I can even assign values to minutes or seconds using

a[1] = 5;
a[0] = 10;

My code :

#include <iostream>

using namespace std;

class Interval
{

public:

    long minutes;
    long seconds;

    Interval(long m, long s)
    {
        minutes = m + s / 60;
        seconds = s % 60;
    }

    void Print() const
    {
        cout << minutes << ':' << seconds << endl;
    }

    long operator[](int index) const
    {
        if(index == 0)
            return seconds;

        return minutes;
    }

};

int main(void)
{
    Interval a(5, 75);
    a.Print();
    cout << endl;

    cout << a[1] << "min and " << a[0] << "sec" << endl;
    cout << endl;

}

I know I have to declare member variables as private, but I have declared here as public just for my convenience.

like image 369
Searock Avatar asked Oct 04 '10 10:10

Searock


People also ask

How can subscript operator be overloaded?

The subscript operator [] is normally used to access array elements. This operator can be overloaded to enhance the existing functionality of C++ arrays.

Does R support operator overloading?

Does R not support operator overloading? @David Heffernan It does. But does not allow to redefine some object (functions, operators, constants). Check another question about it on stackoverflow.

What is operator overloading overload <= operator with example?

This means C++ has the ability to provide the operators with a special meaning for a data type, this ability is known as operator overloading. For example, we can overload an operator '+' in a class like String so that we can concatenate two strings by just using +.

How do you overload double subscripts in C++?

There isn't a double-subscript operator in C++. What you can do is overload operator[] to return an object that also overloads operator[] . This will enable you to write m[i][j] .


2 Answers

Return a reference to the member in question, instead of its value:

long &operator[](int index)
{
    if (index == 0)
        return seconds;
    else
        return minutes;
}
like image 122
Fred Foo Avatar answered Sep 22 '22 22:09

Fred Foo


Change the function signature by removing the const and returning a reference:

long& operator[](int index)

Now you will be able to write statements like:

a[0] = 12;
like image 37
Vijay Mathew Avatar answered Sep 22 '22 22:09

Vijay Mathew