重载+ =用于链操作

Le *_*Anh 0 c++ overloading vector

比方说我有:

class Date {
    int year, month, day;
}
Run Code Online (Sandbox Code Playgroud)

我有+运算符重载:

friend CDate operator +(const Date &leftDate, const Date &rightDate) {}
Run Code Online (Sandbox Code Playgroud)

我在正确的日期增加左边的日期.那部分似乎有效.

现在我想超载+=,如果我所做的一切都是微不足道的date += another_date.

但是,如果我不得不链它,比如:date += another_date + another_date_2我要创建一个向量,another_dateanother_date2会被保存,然后做加法为他们每个人依次是:

Date& Date::operator +=(const vector<Date> &dates) {
    for(auto date: dates) {
        this->year += date.year;
        this->month += date.month;
        this->day += date.day;
    }
    return *this;
}
Run Code Online (Sandbox Code Playgroud)

我现在正在努力的部分是如何重载+运算符,它返回一个向量?

我的想法到目前为止:

  • vector<Date> operator +(const Date &date):我在哪里创建一个向量?我必须创建一个才能插入date.
  • vector<Date> operator +(vector<Date> &dates, const Date &date):类似的问题,我到目前为止还没有创建过矢量.

那么如何重载+运算符,它返回一个向量?

R S*_*ahu 5

当你使用

date += another_date + another_date_2;
Run Code Online (Sandbox Code Playgroud)

它被解释为:

date += (another_date + another_date_2);
Run Code Online (Sandbox Code Playgroud)

我认为这正是你想要的.

不需要任何vector物体.

你也可以使用

date += (another_date + another_date_2 + another_date_3 + another_date_4 + ...);
Run Code Online (Sandbox Code Playgroud)

再一次,不需要任何vector物体.

  • @LeNguyenDuyAnh,没有.`a + = b + c`是'a + =(b + c)`.查看[Operator Precedence]上的cppreference.com页面(http://en.cppreference.com/w/cpp/language/operator_precedence). (3认同)