为什么重载ostream';s操作员<&书信电报;“需要一份参考资料”&&引用;? 我一直在学习C++。< /P>

为什么重载ostream';s操作员<&书信电报;“需要一份参考资料”&&引用;? 我一直在学习C++。< /P>,c++,operator-overloading,C++,Operator Overloading,我理解重载“示例 void f(int& index) { index = 3; } 意味着f是一个带有int参数的函数,该参数通过引用传递 int a = 4; f(a); a的值为3。对于您提到的操作符,这意味着ostream以及对象可能会在操作符执行期间发生更改(作为某种函数) 为什么这个函数在ostream和Object的末尾需要“&” 因为您通过引用传递它们。 为什么要通过引用传递它们。以防止复制 ostream& operator<<(ostr

我理解重载“示例

void f(int& index)
{
    index = 3;
}
意味着
f
是一个带有
int
参数的函数,该参数通过引用传递

int a = 4;
f(a);
a
的值为
3
。对于您提到的操作符,这意味着
ostream
以及
对象
可能会在操作符执行期间发生更改(作为某种函数)

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

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

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

通过引用传递对象是为了防止复制它,同时确保对象引用始终有效(与指针相比)。最好的答案是+1以获得详细解释。更重要的是,即使这样做有任何技术意义,您也不希望复制流。
int a = 4;
f(a);
ostream& operator<<(ostream& out, Objects const& obj)
                             //           ^^^^^       note the const
                             //                       we don't need to modify
                             //                       the obj while printing.
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;
    }
};