简体   繁体   English

什么时候必须重载运算符<<?

[英]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.

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