重载下标运算符“[]”在l值和r值情况下 [英] 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.
例如:我可以使用这个语句
cout<< a [1]< min和< a [0]< sec< endl;
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;
我的代码:
#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.
推荐答案
返回对相关成员的引用,而不是其值:
Return a reference to the member in question, instead of its value:
long &operator[](int index)
{
if (index == 0)
return seconds;
else
return minutes;
}
这篇关于重载下标运算符“[]”在l值和r值情况下的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!