一个关于<<运算符重载传参的疑惑,该如何解决
一个关于<<运算符重载传参的疑惑
请大家帮着看看以下程序段,我不太明白opertaor < <是如何工作,如何传参的。
#include <iostream>
#include <iomanip>
using namespace std;
class Time
{
int hour, minute, second;
public:
void set(int h, int m, int s)
{
hour=h; minute=m; second=s;
}
friend Time& operator++(Time& a);
friend Time operator++(Time& a, int);
friend ostream& operator < <(ostream& o, const Time& t);
};
Time& operator++(Time& a)
{
if(!(a.second=(a.second+1)%60) && !(a.minute=(a.minute+1)%60))
a.hour=(a.hour+1)%24;
return a;
}
Time operator++(Time& a, int)
{
Time t(a); // Time t = a;
if(!(a.second=(a.second+1)%60) && !(a.minute=(a.minute+1)%60))
a.hour=(a.hour+1)%24;
return t;
}
ostream& operator < <(ostream& o, const Time& t)
{
return o < <setfill( '0 ') < <setw(2) < <t.hour < < ": " < <setw(2) < <t.minute < < ": "
< <setw(2) < <t.second < < "\n " < <setfill( ' ');
}
int main()
{
Time t;
t.set(11,59,58);
cout < <t++; //operator++(t,1); 参数1好像没有用?
cout < <++t; //operator++(t);
}
ostream& operator < <(ostream& o, const Time& t) 中,o是引用了哪里?? t应用了t++中的t,但是怎么对应传递的啊?
------解决方案--------------------
o引用了cout.
cout < < t++;相当于下面两句的简写:
operator < <(cout, t);
t++;
operator++(Time&a,int)中的int是语言规定的,为了区别t++与++t的。
------解决方案--------------------
++t是先把自己的值增大一然后再使用t,也就是说在cout < <++t;时,现把自己增大一,然后打印出来
请大家帮着看看以下程序段,我不太明白opertaor < <是如何工作,如何传参的。
#include <iostream>
#include <iomanip>
using namespace std;
class Time
{
int hour, minute, second;
public:
void set(int h, int m, int s)
{
hour=h; minute=m; second=s;
}
friend Time& operator++(Time& a);
friend Time operator++(Time& a, int);
friend ostream& operator < <(ostream& o, const Time& t);
};
Time& operator++(Time& a)
{
if(!(a.second=(a.second+1)%60) && !(a.minute=(a.minute+1)%60))
a.hour=(a.hour+1)%24;
return a;
}
Time operator++(Time& a, int)
{
Time t(a); // Time t = a;
if(!(a.second=(a.second+1)%60) && !(a.minute=(a.minute+1)%60))
a.hour=(a.hour+1)%24;
return t;
}
ostream& operator < <(ostream& o, const Time& t)
{
return o < <setfill( '0 ') < <setw(2) < <t.hour < < ": " < <setw(2) < <t.minute < < ": "
< <setw(2) < <t.second < < "\n " < <setfill( ' ');
}
int main()
{
Time t;
t.set(11,59,58);
cout < <t++; //operator++(t,1); 参数1好像没有用?
cout < <++t; //operator++(t);
}
ostream& operator < <(ostream& o, const Time& t) 中,o是引用了哪里?? t应用了t++中的t,但是怎么对应传递的啊?
------解决方案--------------------
o引用了cout.
cout < < t++;相当于下面两句的简写:
operator < <(cout, t);
t++;
operator++(Time&a,int)中的int是语言规定的,为了区别t++与++t的。
------解决方案--------------------
++t是先把自己的值增大一然后再使用t,也就是说在cout < <++t;时,现把自己增大一,然后打印出来