gpt4 book ai didi

c++ - Ostream << 重载困惑

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:02:57 25 4
gpt4 key购买 nike

当您为类重载 << 运算符时(假装它在 SomeClass 中被定义为 friend ),为什么你们都引用了 ostream 并返回了 ostream?

ostream& operator<<(ostream& s, const SomeClass& c) {
//whatever
return s;
}

当 ostream 已经可以通过引用直接修改时,返回 ostream 有什么好处?这对我来说似乎是多余的 - 虽然我确定它不是 :)

最佳答案

它允许将输出“链接”在一起。如:

std::cout << someObj << someValue;

这等同于:

operator<<(operator<<(std::cout, someObj), someValue);

关于c++ - Ostream << 重载困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7180731/

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