我在类 Interval 中重载了 [] 运算符以返回分钟 或秒。
但我不确定如何使用 [] 运算符将值分配给 minutes 或 second。
例如:我可以使用这个语句
cout << a[1] << "min and " << a[0] << "sec" << endl;
但我想重载 [] 运算符,这样我什至可以使用 给分钟或秒赋值
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;
}
我知道我必须将成员变量声明为私有(private)的,但为了方便我在这里声明为公共(public)的。
最佳答案
返回对相关成员的引用,而不是其值:
long &operator[](int index)
{
if (index == 0)
return seconds;
else
return minutes;
}
关于c++ - 在左值和右值情况下重载下标运算符 "[ ]",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3854419/