Overloading the subscript operator “[ ]” in the l-

2020-07-11 06:35发布

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.

7条回答
smile是对你的礼貌
2楼-- · 2020-07-11 07:03

return by reference to be able to assign values and use them on the LHS of the assignment operator.

查看更多
登录 后发表回答