重载后缀++不明白的地方
返回const:
const Byte Byte::operator++(int)----------------//第一种写法
{
Byte Before(*this);
++(*this)
return Before;
}
返回非const:
Byte Byte::operator++(int)-------------------//第二种写法
{
Byte Before(*this);
++(*this)
return Before;
}
在c++编程思想的P279页中对后缀重载返回值有说明,operator++(int)返回临时对象,临时对象自动为常量。
调用方式:
Byte a;
(a++).func() ///func为非const成员
对于第一种写法编译器肯定会报错,但对于第二种写法编译器并没报错,按照c++编程思想的说法,编译器会阻止,是编译器的原因吗?
我知道第二种写法会导致a++++的问题,违背了++++的语义,不建议使用,所以返回const。