[英]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.