【发布时间】:2011-04-20 17:52:25
【问题描述】:
我在班级 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;
}
我知道我必须将成员变量声明为私有,但我在这里声明为公共只是为了方便。
【问题讨论】:
-
这似乎是一个糟糕的运算符重载示例。您是否有一些模糊的要求迫使您这样做?否则只是代码混淆。
-
@jalf 我知道这是一个糟糕的例子,但我想在 Object Array 的泛型类中重载 [] 运算符。
-
@jalf: 为什么cpp.sh/4fiz 工作时没有任何编译器错误?编译器不应该抛出错误吗?它不提供任何输出。这个程序到底发生了什么。
标签: c++ operator-overloading subscript-operator