【问题标题】:QuantLib date ++ operator overloadingQuantLib 日期++ 运算符重载
【发布时间】:2020-04-27 20:41:02
【问题描述】:

由于某种原因,QuantLib 的 Date 对象 ++ 重载运算符没有按预期工作,但我不明白为什么它没有工作。谁能指出原因?

以下测试代码中没有错误或警告。

#include <ql/quantlib.hpp>
#include <ql/time/date.hpp>
#include <iostream>

int main()
{
        QuantLib::Date today = QuantLib::Date::todaysDate();

        std::cout << "today's date is " << today << std::endl;
        std::cout << "tomorrow is " << today++ << std::endl;
        std::cout << "tomorrow is " << today+1 << std::endl;

        return 0;
}

返回是:

today's date is April 27th, 2020
tomorrow is April 27th, 2020
tomorrow is April 29th, 2020

似乎 ++ 运算符增加了日期但未正确显示,因此 Date+1 实际上再次增加到 29。看起来 ++ 和 + 运算符之间的区别是(在 date.hpp 中):

Date& operator++()
Date  operator++(int )
Date operator+(Date::serial_type days) const;
Date operator+(const Period&) const;

本质上 ++ 在 Boost 中使用 Gregorian 对象(在 date.cpp 中)

Date& Date::operator++() {
        dateTime_ +=boost::gregorian::days(1);
        return *this;
    }
Date Date::operator+(Date::serial_type days) const {
        Date retVal(*this);
        retVal+=days;

        return retVal;
    }

【问题讨论】:

    标签: c++ quantlib


    【解决方案1】:

    ++ 出现在变量名之后时,它被称为“后缀”增量运算符。这将返回变量的副本,然后递增变量本身。这不一定是后缀增量运算符的所有重载必须如何工作,但它是常规的:

    int i = 5;
    int j = i++; //here j is 5
    //i is now 6
    

    要获得您所追求的行为,您可以使用“前缀”递增运算符,其中++ 位于变量名称之前。这会增加变量,然后返回对它的引用:

    int i = 5;
    int j = ++i; //here j is 6, as is i
    

    重载运算符时,重载后缀运算符需要一个虚拟参数,而重载前缀运算符则不需要。从你的例子:

    Date& operator++(); //prefix increment operator
    Date  operator++(int) //postfix increment operator
    

    因此,要增加日期变量并返回对它的引用,请使用:

    std::cout << "tomorrow is " << ++today << std::endl; //prefix operator
    

    【讨论】:

    • 哦,date.hpp 确实说 ++() 是前增量,而 ++(int) 是后增量。在这种情况下,我没有意识到 pre/post-increment 意味着 pre/post-fix。感谢您指出。
    猜你喜欢
    • 1970-01-01
    • 2017-12-18
    • 1970-01-01
    • 2016-02-19
    • 1970-01-01
    • 2011-06-21
    • 2012-09-14
    相关资源
    最近更新 更多