Ostream<重载混乱 [英] Ostream << overloading confusion
问题描述
当您重载<< (假定这是在SomeClass中定义为一个朋友),为什么你们都参考ostream并返回ostream?
When you're overloading the << operator for a class (pretend this is defined as a friend in SomeClass), why do you both take a reference to the ostream and return that ostream?
ostream& operator<<(ostream& s, const SomeClass& c) {
//whatever
return s;
}
当ostream已经可以通过引用直接修改时,这看起来对我来说是多余的 - 虽然我确定不是:)
What benefit can returning the ostream be when it was already directly modifiable by reference? This seems redundant to me - though I'm sure it's not :)
推荐答案
这不是多余的, 。使用std :: string :: append这样的函数更容易看到,所以我将从这里开始:
This is not redundant, but useful for chaining calls. It's easier to see with functions like std::string::append, so I'll start with that:
std::string mystring("first");
mystring.append(" second");
mystring.append(" third");
可以重写为:
std::string mystring("first").append(" second").append(" third");
这是可能的,因为.append()返回对它修改的字符串的引用,添加.append(...)到结束。与你正在做的事情相关的代码正在改变:
This is possible because .append() returns a reference to the string it modified, so we can keep adding .append(...) to the end. The code correlating to what you are doing is changing from this:
std::cout << "first";
std::cout << " second";
std::cout << " third";
因为运算符<返回流,我们也可以链接这些!
into this. Since operator<< returns the stream, we can also chain these!
std::cout << "first" << " second" << " third";
看到相似性和有用性?
这篇关于Ostream<重载混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!