我重载了前缀和后缀的递增和递减运算符。我可以打电话给他们,他们在分配作业中工作得很好,而且只能“靠自己”工作。 但是,我不能从与 prefixed 运算符一起使用的对象中调用成员函数。一切都可以用后缀表示法很好地工作。 编译器给我两个错误:
我不明白为什么会这样。
谢谢。
#include<iostream>
using namespace std; //I know I shouldn't do this in real projects
class Time
{
public:
Time() : hrs(0), mins(0), secs(0) {};
Time(int m_hrs, int m_mins, int m_secs) : hrs(m_hrs), mins(m_mins), secs(m_secs) {};
void display()
{
cout << hrs << ':' << mins << ':' << secs;
} const
Time operator+(Time time) const
{
int tmp_hrs = hrs + time.hrs;
int tmp_mins = mins + time.mins;
int tmp_secs = secs + time.secs;
if (tmp_secs >= 60)
{
tmp_secs -= 60;
tmp_mins++;
}
if (tmp_mins >= 60)
{
tmp_mins -= 60;
tmp_hrs++;
}
if (tmp_hrs >= 24)
{
tmp_hrs -= 24;
}
return { tmp_hrs, tmp_mins, tmp_secs };
}
Time operator++()
{
Time tmp(hrs, mins, secs);
tmp.secs++;
tmp.resolve_overflow();
hrs = tmp.hrs;
mins = tmp.mins;
secs = tmp.secs;
return tmp;
}
Time operator++(int)
{
Time to_return(hrs, mins, secs);
Time tmp(hrs, mins, secs);
tmp.secs++;
tmp.resolve_overflow();
hrs = tmp.hrs;
mins = tmp.mins;
secs = tmp.secs;
return to_return;
}
Time operator--()
{
Time tmp(hrs, mins, secs);
tmp.secs--;
tmp.resolve_underflow();
hrs = tmp.hrs;
mins = tmp.mins;
secs = tmp.secs;
return tmp;
}
Time operator--(int)
{
Time to_return(hrs, mins, secs);
Time tmp(hrs, mins, secs);
tmp.secs--;
tmp.resolve_underflow();
hrs = tmp.hrs;
mins = tmp.mins;
secs = tmp.secs;
return to_return;
}
private:
int hrs;
int mins;
int secs;
void resolve_overflow()
{
if (secs >= 60)
{
secs -= 60;
mins++;
}
if (mins >= 60)
{
mins -= 60;
hrs++;
}
if (hrs >= 24)
{
hrs -= 24;
}
}
void resolve_underflow()
{
if (secs < 0)
{
secs = 59;
mins--;
}
if (mins < 0)
{
mins = 59;
hrs--;
}
if (hrs < 0)
{
hrs = 23;
}
}
};
int main()
{
Time t1(0,0,0);
++t1.display(); cout << endl;
return 0;
}
答案 0 :(得分:2)
您正在尝试增加void(这是display()的返回类型)。
这清楚表明++是针对对象的。
int main()
{
Time t1(0,0,0);
(++t1).display(); cout << endl;
return 0;
}
此外,我不确定为什么要为前缀operator ++创建随机对象。为什么不像基本类型那样通过引用返回相同的对象?
Time& operator++()
{
this->secs++;
resolve_overflow();
return *this;
}