我重载[]运算符在我的课间隔返回分钟或秒。重载下标运算符“[]”中的L值和R值的情况下
但我不确定如何使用[]运算符将值分配给分钟或第二个。
例如:我可以用这个语句
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;
}
I知道我必须将成员变量声明为私有的,但为了方便起见,我已经在这里声明为public。
这似乎是一个运算符重载的可怕例子。你有一些晦涩的要求,迫使你这样做?否则,它只是代码混淆。 – jalf 2010-10-04 10:55:15
@jalf我知道这是一个可怕的例子,但我想在对象数组的泛型类中重载[]运算符。 – Searock 2010-10-04 11:06:36
@jalf:为什么http://cpp.sh/4fiz没有任何编译器错误?不应该编译器抛出一个错误?它没有提供任何输出。这个计划究竟发生了什么。 – Destructor 2016-05-09 09:03:08