我正在阅读 Bjarne Stroustrups 使用 C++ 的原理和实践。在关于运算符重载的第 9.6 章中,他给出了以下示例:
enum class Month {
Jan=1, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec
};
Month operator++(Month& m) // prefix increment operator
{
m = (m==Month::Dec) ? Month::Jan : Month(static_cast<int>(m)+1);
return m;
}
作为为枚举类
++
定义递增运算符 Month
的示例。然后他说可以这样使用:
Month m = Month::Sep;
++m; // m becomes Oct
++m; // m becomes Nov
++m; // m becomes Dec
++m; // m becomes Jan (“wrap around”)
但是当您通过引用传递 Month 对象并更改它时,我不明白返回 Month 的意义。为什么不这样写函数:
void operator++(Month& m) // prefix increment operator
{
m = (m==Month::Dec) ? Month::Jan : Month(static_cast<int>(m)+1);
}
我测试时代码运行良好。我想知道我忽略了什么,因为这个 Stroustrup 人非常了解这种语言:)
当您重写运算符时,您应该以预期的方式重写它们。
您可能测试过类似的内容:
Month month = Month::SEP;
++month;
但是如果你尝试做这样的事情会发生什么:
Month October = ++month;
这应该是一个合法的操作,但是你的
operator++()
方法返回void,所以它无法正常工作。
operator++()方法的返回需要返回对象,因为人们会在表达式中使用
++foo
。