簡體   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;
}

我何時必須重載operator <<

我認為既然arr有整數,所以我不應該重載<<

盡管您的X只是單個int屬性的包裝,但它與int是不同的類型。 好消息是,您可以通過添加以下函數來委托給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