[英]When must I overload operator <<?
#include <iostream>
using namespace std;
struct X{
int _x;
X(int x=0):_x(x){}
};
int main() {
X arr[5];
for (int i = 0;i < 5;i++) {
arr[i] = i;
}
for (int i = 0;i < 5;i++) {
cout << arr[i] <<",";
}
return 0;
}
When must I overload operator <<
? 我何时必须重载
operator <<
?
I think since arr
has ints so I shouldn't overload <<
? 我认为既然
arr
有整数,所以我不应该重载<<
?
Although your X
is just a wrapper around a singular int
property it is a different type than int
. 尽管您的
X
只是单个int
属性的包装,但它与int
是不同的类型。 The good news is you can just delegate to the int
method by adding this function: 好消息是,您可以通过添加以下函数来委托给
int
方法:
std::ostream& operator<<(std::ostream& o, const X& x) {
o << x._x;
return o;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.