简体   繁体   English

使用重载后减运算符时,为什么需要在<<重载函数中使用const引用参数?

[英]Why do I need to use a const reference parameter in a << overloading function when using an overloaded post-decrement operator?

I have the following << overloading function: 我有以下<<重载函数:

ostream& operator<<(ostream& output, HW4& rhs)
{

    for(int i = 0; i < HW4::size; ++i)
    {
        output << rhs.array[i] << "    ";
    }

    return output;
}

And I also have this post-decrement overloading function: 我还具有以下递减后重载功能:

HW4 HW4::operator--(int)
{
    HW4 temp = *this;
    int hold;
    for(int i = 0; i < size/2; ++i)
    {
        hold = array[i];
        array[i] = array[size - i - 1];
        array[size - i - 1] = hold;
    }

    return temp;
}

I don't understand why 我不明白为什么

cout << object2-- << endl << endl; cout << object2-- << endl << endl;

won't compile unless I change the << overloading function to have a const reference parameter like this 除非我将<<重载函数更改为具有这样的const引用参数,否则不会编译

ostream& operator<<(ostream& output, const HW4& rhs)

HW4::operator--(int) returns by value, then what object2-- returns would be a temporary object which can't be bound to an lvalue reference to non-const. HW4::operator--(int)按值返回,那么object2--返回的将是一个临时对象,该对象不能绑定到对非const的左值引用。

On the other hand, temporary object can be bound to lvalue reference to const . 另一方面,可以将临时对象绑定到const左值引用。 That's why making operator<< taking const HW4& works. 这就是为什么让operator<< const HW4&起作用的原因。 Conventionally operator<< is supposed for outputting only, it shouldn't change the object passed; 通常, operator<<仅用于输出,不应更改传递的对象; so you should declare operator<< taking const HW4& as the parameter. 因此,您应使用 const HW4&作为参数声明operator<<

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法在函数调用中使用int后减 - Cannot use int post-decrement in function call 为什么在后面的运算符重载中需要使用const? - Why do you need to use const in following operator overloading? 为什么在重载下标运算符时使用const int参数? - Why use const int parameter when overloading the subscript operator? 在运算符重载中将Friend函数与const引用一起使用 - using friend function with const reference in operator overloading 为什么运算符&gt;&gt;(或&lt;&lt;)重载函数需要接收i \\ ostream引用? - Why does operator>> (or <<) overloading function need to receive an i\ostream reference? 在运算符重载中使用“ const”作为参数 - use “const” as parameter in operator overloading 运算符重载后递减 - Operator Overloading Post Decrement C ++中的运算符重载 - 为什么我们需要将参数作为const&(...)传递? - Operator overloading in C++ - why do we need to pass parameter as const & (…)? 在C ++中,为什么我们在重载函数中将引用参数声明为const? - in c++ why we declare reference parameter as const in overloaded function? 为什么重载的new运算符正在调用构造函数,即使我在重载函数中使用malloc? - why overloaded new operator is calling constructor even I am using malloc inside overloading function?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM