【问题标题】:Why do I need to use a const reference parameter in a << overloading function when using an overloaded post-decrement operator?为什么在使用重载的后减运算符时,我需要在 << 重载函数中使用 const 引用参数?
【发布时间】:2017-11-18 04:52:45
【问题描述】:

我有如下&lt;&lt;重载函数:

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

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

    return output;
}

而且我也有这个后递减重载函数:

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

我不明白为什么

cout

除非我将 &lt;&lt; 重载函数更改为具有这样的 const 引用参数,否则不会编译

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

【问题讨论】:

  • operator-- 返回一个临时的。临时不能绑定到非常量左值引用。
  • 如果&lt;&lt; 改变了rhs 的值,你会让很多人感到奇怪。使用const,卢克。

标签: c++ reference operator-overloading constants


【解决方案1】:

HW4::operator--(int) 按值返回,那么object2-- 返回的将是一个临时对象,它不能绑定到对非 const 的左值引用。

另一方面,临时对象可以绑定到对const 的左值引用。这就是为什么让operator&lt;&lt;const HW4&amp; 起作用的原因。通常operator&lt;&lt; 应该只用于输出,它不应该改变传递的对象;所以你应该声明operator&lt;&lt;const HW4&amp; 作为参数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多