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.
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 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.
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 +.
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] .
Return a reference to the member in question, instead of its value:
long &operator[](int index)
{
if (index == 0)
return seconds;
else
return minutes;
}
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With