gpt4 book ai didi

c++ - 重载的返回值<<

转载 作者:太空狗 更新时间:2023-10-29 20:05:49 24 4
gpt4 key购买 nike

#include <iostream>

using namespace std;

struct info {
info(int x, int y) : x(x), y(y) {}
int x;
int y;
};

ostream& operator<<(ostream& out, const info &myinfo){
out << myinfo.x << " " << myinfo.y;
return cout;
}

int main() {
info a(1,2);
info b(3,4);
cout << a << " " << b << endl;
}

即使不正确地重载 operator <<,上述程序的输出看起来也不错.

谁能告诉我这个重载问题的影响是什么?我知道重载函数应该返回 out而不是 cout , 但上述版本的行为如何?

最佳答案

在这种情况下,因为您要传入 std::cout到重载operator<< , 行为上没有区别。不过,通常情况下,您会导致 " " << b << std::endl发送至 std:cout , 而你的 a将转到您传入的任何内容。

例如:

info a(1,2);
info b(3,4);
std::ostringstream ss;
ss << a << " " << b << std::endl;

会导致ass .

关于c++ - 重载的返回值<<,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11284056/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com