我重载了 I/O 运算符:
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;
最佳答案
cin >> time;
这是运算符 >>>
有两个操作数。如果发现重载运算符函数为非成员,则左操作数成为第一个参数,右操作数成为第二个参数。于是就变成了:
operator>>(cin, time);
所以 cin
参数只是运算符的第一个操作数。
参见标准的 §13.5.2:
A binary operator shall be implemented either by a non-static member function (9.3) with one parameter or by a non-member function with two parameters. Thus, for any binary operator
@
,x@y
can be interpreted as eitherx.operator@(y)
oroperator@(x,y)
.
如果您想知道这如何应用于链式运算符,请看:
cin >> time >> something;
这相当于:
(cin >> time) >> something;
这也等同于:
operator>>(operator>>(cin, time), something);
关于c++ - C++ 如何确定重载运算符的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15429265/