为什么重载ostream的运算符<<需要参考“&"吗? [英] Why does overloading ostream's operator<< need a reference "&"?
问题描述
我一直在学习C ++.
I've been learning C++.
在此页面上,我了解到重载<<"ostream的运算符可以通过这种方式完成.
From this page, I understood that overloading "<<" operator of ostream can be done in this way.
ostream& operator<<(ostream& out, Objects& obj) {
//
return out;
}
//Implementation
和
friend ostream& operator<<(ostream& out, Object& obj);
//In the corresponding header file
我的问题是...为什么此功能需要&"在 ostream
和 Object
的末尾?
My question is... why does this function need "&" at the end of ostream
and Object
?
至少我知道&"用来...
At least I know that "&" is used to...
- 获取值的地址
- 声明对类型的引用
但是,我认为它们均不适用于上述重载.我花了很多时间在谷歌上阅读和阅读教科书,但找不到答案.
However, I think neither of them applies to the overloading described above. I've spent a lot of time in googling and reading a text book, but I can't find the answer.
任何建议将不胜感激.
推荐答案
为什么此功能需要&"在ostream和Object的末尾?
why does this function need "&" at the end of ostream and Object?
因为您要通过引用传递它们.
您为什么要通过引用传递它们.为了防止复制.
Because you are passing them by reference.
Why are you passing them by reference. To prevent a copy.
ostream& operator<<(ostream& out, Objects const& obj)
// ^^^^^ note the const
// we don't need to modify
// the obj while printing.
obj
可以被复制(潜在地).但是,如果复制成本很高,该怎么办.因此最好通过引用将其传递,以防止不必要的复制.
The obj
can be copied (potentially). But what if it is expensive to copy. So best to pass it by reference to prevent an unnecessary copy.
out
的类型为 std :: ostream
.不能复制(复制构造函数已禁用).因此,您需要通过引用.
The out
is of type std::ostream
. This can not be copied (the copy constructor is disabled). So you need to pass by reference.
我通常在类声明中直接声明流运算符:
I normally declare the stream operator direcctly in the class declaration:
class X
{
std::string name;
int age;
void swap(X& other) noexcept
{
std::swap(name, other.name);
std::swap(age, other.age);
}
friend std::ostream& operator<<(std::ostream& str, X const& data)
{
return str << data.name << "\n" << age << "\n";
}
friend std::istream& operator>>(std::istream& str, X& data)
{
X alt;
// Read into a temporary incase the read fails.
// This makes sure the original is unchanged on a fail
if (std::getline(str, alt.name) && str >> alt.age)
{
// The read worked.
// Get rid of the trailing new line.
// Then swap the alt into the real object.
std::string ignore;
std::getline(str, ignore);
data.swap(alt);
}
return str;
}
};
这篇关于为什么重载ostream的运算符<<需要参考“&"吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!