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

标签 c++ arguments operator-overloading istream ostream

我重载了 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 either x.operator@(y) or operator@(x,y).

如果您想知道这如何应用于链式运算符,请看:

cin >> time >> something;

这相当于:

(cin >> time) >> something;

这也等同于:

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

关于c++ - C++ 如何确定重载运算符的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15429265/

相关文章:

c++ - 关于传递参数在 C++ 中如何工作的问题

c# - "' BaseClass ' does not contain a constructor that takes 0 arguments."部分 C#/Protobuf 类

c++ - c_str == string 与 c_str == c_str 的值相等

c++ - 在 GoogleTest 中使用 ASSERT 和 EXPECT

java - Java/OOP 编程中传递参数、好的和坏的实践

C++重载函数名查找错误

c++ - 有没有办法在指向类类型的指针中不使用 * 来调用类运算符?

c++ - 从 QPushbutton 继承的类不显示文本

c++ - 英特尔 <math.h> vs C <math.h>?

c# - 在 C# 中是否可以通过以下方式重载泛型转换运算符?