C++中为Date类重载+=运算符以支持链式操作的问题
首先得说,你完全不需要用vector来存储那些日期对象——其实链式操作比如date += another_date + another_date_2的逻辑比你想的简单多了,咱们一步步理清楚:
核心逻辑拆解
当你写date += another_date + another_date_2时,编译器会先执行右边的another_date + another_date_2,因为加法的优先级高于+=。而你已经实现了operator+,它会返回一个新的Date(或者你写的CDate)临时对象,这个临时对象就是前两个日期相加后的结果。接下来,这个临时对象会作为参数传给date的operator+=——和你直接写date += some_single_date的场景完全一样!
所以问题的关键根本不是存储多个日期,而是正确实现operator+=,让它既能接受临时对象,又能支持链式调用(比如date1 += date2 += date3这种场景)。
正确的operator+=实现方式
按照C++运算符重载的惯例,operator+=应该是成员函数(因为它需要修改左操作数的状态),并且返回Date&(当前对象的引用)来支持链式操作。而且你已经有了正确的operator+,完全可以复用它的逻辑,避免重复造轮子:
class Date { int year, month, day; public: // 补上必要的构造函数(示例用) Date(int y, int m, int d) : year(y), month(m), day(d) {} // 你已经实现好的友元operator+ friend Date operator+(const Date& leftDate, const Date& rightDate) { // 你的日期递增逻辑(已验证正常) Date result = leftDate; // 这里写你已经调试好的日期相加逻辑:比如按rightDate的年/月/日递增result // 示例简化逻辑(实际要处理进位): result.day += rightDate.day; result.month += rightDate.month; result.year += rightDate.year; return result; } // 重点:实现支持链式的operator+= Date& operator+=(const Date& rhs) { // 复用已有的operator+逻辑,避免重复写日期递增代码 *this = *this + rhs; // 返回当前对象的引用,支持链式操作 return *this; } };
验证链式操作
现在你可以直接用这些场景测试:
- 基础场景:
date += another_date - 你需要的场景:
date += another_date + another_date_2 - 更复杂的链式:
date1 += date2 += date3(这里date2 += date3会返回date2的引用,然后date1再加上这个引用指向的date2)
为什么不需要vector?
你可能误以为要把another_date和another_date_2分别存储再依次相加,但实际上another_date + another_date_2已经通过你写的operator+合并成了一个单一的Date对象——你只需要把这个合并后的结果加到date上就行,完全不需要额外存储中间的多个日期。
内容的提问来源于stack exchange,提问作者Sorry

