繁体   English   中英

C ++如何确定重载运算符的参数?

[英]How C++ determine arguments of overloaded operators?

我有重载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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM