为什么重载ostream的运算符<<需要引用"&"?

Hir*_*oki 6 c++ operator-overloading

我一直在学习C++.

从这个页面,我明白ostream的重载"<<"运算符可以通过这种方式完成.

ostream& operator<<(ostream& out, Objects& obj) {
    //
    return out;
} 
//Implementation
Run Code Online (Sandbox Code Playgroud)

friend ostream& operator<<(ostream& out, Object& obj);
//In the corresponding header file
Run Code Online (Sandbox Code Playgroud)

我的问题是...为什么这个功能需要"和"在结束ostreamObject

至少我知道"&"习惯了......

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

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

任何建议将被认真考虑.

Mar*_*ork 13

为什么这个函数在ostream和Object的末尾需要"&"?

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

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

obj可复制(可能).但如果复制起来很昂贵呢?因此最好通过引用传递它以防止不必要的副本.

out是类型std::ostream.无法复制(禁用复制构造函数).所以你需要通过引用传递.

我通常在类声明中直接声明流操作符:

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;
    }
};
Run Code Online (Sandbox Code Playgroud)