2013-03-15 18 views
1

我重载I/O操作符:C++如何确定重载运算符的参数?

struct Time { 
    int hours; 
    int minutes; 
}; 

ostream &operator << (ostream &os, Time &t) { 
    os << setfill('0') << setw(2) << t.hours; 
    os << ":"; 
    os << setfill('0') << setw(2) << t.minutes; 
    return os; 
} 

istream &operator >> (istream &is, Time &t) { 
    is >> t.hours; 
    is.ignore(1, ':'); 
    is >> t.minutes; 
    return is; 
} 

我想知道我什么时候叫cin >> time如何编译确定is &is说法。这里是我的main()程序:

operator>>(cin, time); 
cout << time << endl; 

cin >> (cin , time); 
cout << time << endl; 

cin >> time;      //Where is cin argument??? 
cout << time << endl; 

回答

4
cin >> time; 

这是运营商>>有两个操作数。如果重载操作符函数被发现为非成员,则左操作数成为第一个参数,右操作数成为第二个参数。因此,它变成了:

operator>>(cin, time); 

所以cin说法仅仅是第一个操作数的运算符。

参见标准的§13.5.2:

二元运算应由非静态成员函数(9.3)带有一个参数或通过使用两个参数的非成员函数被实现。因此,对于任何二进制运算符@[email protected]可以被解释为​​或[email protected](x,y)

如果你想知道如何适用于经营链,借此:

cin >> time >> something; 

这相当于:

(cin >> time) >> something; 

这也等同于:

operator>>(operator>>(cin, time), something); 
+0

太棒了!谢谢你,@sftrabbit :-) – 2013-03-15 10:00:17

+0

@MarkGarcia:完成。 – 2013-03-15 10:05:18