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

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

But I'm not sure how to assign values ​​to minutes or second using the [] operator.

For example: I can use this statement

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

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

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

My code is:

#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 that I have to declare member variables as private, but I declared it publicly here just for my convenience.

+5
source share
7 answers

, :

long &operator[](int index)
{
    if (index == 0)
        return seconds;
    else
        return minutes;
}
+10

, const :

long& operator[](int index)

, :

a[0] = 12;
+8

op [] "" , :

cout << a.minutes << "min and " << a.seconds << "sec" << endl;

, , op []. , , , , (, 0 <= < 60).

struct Interval {
  int minutes() const { return _minutes; }
  void minutes(int n) { _minutes = n; }  // allows negative values, etc.

  int seconds() const { return _seconds; }
  void seconds(int n) {
    if (0 <= n and n < 60) {
      _seconds = n;
    }
    else {
      throw std::logic_error("invalid seconds value");
    }
  }

  // rest of class definition much like you have it

private:
  int _minutes, _seconds;
};

// ...
cout << a.minutes() << "min and " << a.seconds() << "sec" << endl;
+6

, LHS .

+3

:

long& operator[](int index) 
+3

-

long& operator[](int index);                    // for non const object expressions

long const& operator[](int index) const;        // for const object expressions
+1

sub script const non-const sub script.

long& operator[](int index);  // non-const function returning reference

long const& operator[](int index) const;// const function returning const reference

A[1] = 5 index 1. , sub script .

cout << A[1] index 1. , const- sub script .

+1

All Articles