c++如何确定重载操作符的参数

How C++ determine arguments of overloaded operators?

本文关键字:参数 操作符 重载 何确定 c++      更新时间:2023-10-16

我重载了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:

二元操作符可以由带一个形参的非静态成员函数(9.3)实现,也可以由带两个形参的非成员函数实现。因此,对于任何二进制运算符@, x@y都可以解释为x.operator@(y)operator@(x,y)

如果你想知道这是如何应用于链式操作符的,看看这个:

cin >> time >> something;

这相当于:

(cin >> time) >> something;

也等价于:

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