【问题标题】:How C++ determine arguments of overloaded operators?C++ 如何确定重载运算符的参数?
【发布时间】:2013-03-03 23:34:19
【问题描述】:

我重载了 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 &gt;&gt; time 时编译器如何确定is &amp;is 参数。这是我的main() 程序:

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

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

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

【问题讨论】:

    标签: c++ arguments operator-overloading istream ostream


    【解决方案1】:
    cin >> time;
    

    这是带有两个操作数的运算符&gt;&gt;。如果重载的运算符函数被发现为非成员,则左操作数成为第一个参数,右操作数成为第二个参数。于是就变成了:

    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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多