std::chrono::operator+, std::chrono::operator- (std::chrono::year)
来自cppreference.com
定义于头文件 <chrono>
|
||
constexpr std::chrono::year operator+(const std::chrono::year& y, const std::chrono::years& ys) noexcept; |
(1) | (C++20 起) |
constexpr std::chrono::year operator+(const std::chrono::years& ys, const std::chrono::year& y) noexcept; |
(2) | (C++20 起) |
constexpr std::chrono::year operator-(const std::chrono::year& y, const std::chrono::years& ys) noexcept; |
(3) | (C++20 起) |
constexpr std::chrono::years operator-(const std::chrono::year& y1, const std::chrono::year& y2) noexcept; |
(4) | (C++20 起) |
1-2) 对
y
加 ys.count()
年。3) 从
y
减去 ys.count()
年。4) 返回
y1
与 y2
间按年计算的差。返回值
1-2) std::chrono::year(int(y) + ys.count())
3) std::chrono::year(int(y) - ys.count())
4) std::chrono::years(int(y1) - int(y2))
注解
若 (1-3) 产生的年份值在范围 [-32767,32767] 外,则实际存储值未指定。
二个 year
值相减的结果是 std::chrono::years 类型时长。此时长单位表示格里高利年的平均长度,而结果与运算数所表示的具体年中的日数无关。例如 2018y - 2017y 的结果是 std::chrono::years(1) ,它表示 365.2425 日,而非 365 日。
示例
运行此代码
#include <iostream> #include <chrono> int main() { std::chrono::year y {2020}; y = y + std::chrono::years(12); if (y == std::chrono::year(2032)) { std::cout << "Years added correctly" << "\n"; } else { std::cout << "Years not added correctly" << "\n"; } y = y - std::chrono::years(33); if (y == std::chrono::year(1999)) { std::cout << "Years subtracted correctly" << "\n"; } else { std::cout << "Years not subtracted correctly" << "\n"; } std::chrono::years ys = std::chrono::year(2025) - std::chrono::year(2020); if (ys == std::chrono::years(5)) { std::cout << "Years subtracted correctly" << "\n"; } else { std::cout << "Years not subtracted correctly" << "\n"; } }
输出:
Years added correctly Years subtracted correctly Years subtracted correctly
返回值
自增或自减 month ( std::chrono::month 的公开成员函数) | |
加或减月数 ( std::chrono::month 的公开成员函数) |