为什么重载ostream的operator<<需要引用“&”?

Why does overloading ostream's operator<< need a reference "&"?

我一直在学习C++。

From this page, 我了解到可以通过这种方式重载 ostream 的“<<”运算符。

ostream& operator<<(ostream& out, Objects& obj) {
    //
    return out;
} 
//Implementation

friend ostream& operator<<(ostream& out, Object& obj);
//In the corresponding header file

我的问题是...为什么这个函数需要在ostreamObject 末尾加上“&”?

至少我知道“&”是用来...

  1. 取一个值的地址
  2. 声明对类型的引用

但是,我认为它们都不适用于上述重载。我花了很多时间在谷歌上搜索和阅读教科书,但找不到答案。

如有任何建议,我们将不胜感激。

例子

void f(int& index)
{
    index = 3;
}

表示 f 是一个带有 int 参数的函数,通过引用传递。所以

之后
int a = 4;
f(a);

a 的值为 3。对于您提到的运算符,这意味着 ostreamObject 可能会在运算符执行期间发生变化(作为某种函数)。

why does this function need "&" at the end of ostream and Object?

因为您是通过引用传递它们。
你为什么要通过引用传递它们。防止复制。

ostream& operator<<(ostream& out, Objects const& obj)
                             //           ^^^^^       note the const
                             //                       we don't need to modify
                             //                       the obj while printing.

obj可以被复制(可能)。但是,如果复制成本很高怎么办。所以最好通过引用传递它以防止不必要的复制。

out 的类型是 std::ostream。这不能被复制(复制构造函数被禁用)。所以你需要通过引用传递。

我通常在 class 声明中直接声明流运算符:

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