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);
相关文章:
- 我可以将C 17 Capture lambda ConstexPR转换操作符的结果用作函数指针模板非类型参数吗?
- 单参数构造函数和赋值操作符
- c++中的操作符重载,无法调用双参数构造函数
- 操作符重载模板参数
- c++操作符重载以指针类型作为参数
- 在覆盖new操作符时传递更多参数(c++)
- 带有不同参数的c++操作符重载模板
- 重载操作符=,不同的类作为参数
- 如何检查类型是否存在无参数操作符()
- 传递静态方法作为参数,不需要地址操作符
- 检索对象的函数操作符的参数类型
- 带有派生类型参数的赋值操作符
- 使用具有不同参数的相同操作符
- 为什么小于操作符接受不同类型的参数,而std::min不接受
- 将构造函数参数转发给放置new操作符
- (为什么)移动构造函数或移动赋值操作符应该清除其参数
- 对操作符()()中具有状态和两个参数的函数对象使用boost绑定
- 比较测试失败:unorder_map上的[]操作符产生的参数数量错误
- 操作符重载和不同的模板参数
- c++如何确定重载操作符的参数