命名空间
变体
操作

std::chrono::duration<Rep,Period>::operator=

来自 cppreference.com
< cpp‎ | chrono‎ | duration
 
 
工具库
语言支持
类型支持 (基本类型,RTTI)
库特性测试宏 (C++20)
动态内存管理
程序工具
协程支持 (C++20)
可变参数函数
调试支持
(C++26)
三元比较
(C++20)
(C++20)(C++20)(C++20)
(C++20)(C++20)(C++20)
通用工具
日期和时间
函数对象
格式化库 (C++20)
(C++11)
关系运算符 (在 C++20 中已弃用)
整数比较函数
(C++20)(C++20)(C++20)   
(C++20)
交换类型操作
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
通用词汇类型
(C++11)
(C++17)
(C++17)
(C++17)
(C++11)
(C++17)
(C++23)
基本字符串转换
(C++17)
(C++17)

 
 
 
duration& operator=( const duration &other ) = default;
(自 C++11 起)

将一个 duration 的内容赋值给另一个。

[编辑] 参数

other - 要复制的 duration

[编辑] 示例

#include <chrono>
#include <iostream>
 
int main()
{
    using namespace std::chrono_literals;
 
    std::chrono::hours z_hours{};
    std::chrono::seconds z_seconds{};
 
    z_hours = 2h; // ok, no conversion needed
 
    z_seconds = z_hours;
    // First, the converting ctor is used to create a temporary object of `lhs`s type.
    // This ctor implicitly invokes the casting function
    // chrono::duration_cast<std::seconds>(z_hours). The resulting `rhs` rvalue
    // has the same type as `lhs`, and the `operator=` finally performs the assignment.
 
    std::cout << "hours: " << z_hours.count() << '\n';
    std::cout << "seconds: " << z_seconds.count() << '\n';
 
    z_seconds -= 42s;
 
//  z_hours = z_seconds; // compile-time error (which is good): incompatible types.
    // The library avoids the implicit cast to prevent a potential precision loss.
 
    z_hours = std::chrono::duration_cast<std::chrono::hours>(z_seconds); // ok
    z_hours = std::chrono::duration_cast<decltype(z_hours)>(z_seconds);  // ditto
 
    std::cout << "hours: " << z_hours.count() << '\n';
    std::cout << "seconds: " << z_seconds.count() << '\n';
 
    std::chrono::duration<double, std::ratio<3600>> z2_hours{};
 
    z2_hours = z_seconds; // ok, no truncation, implicit cast
 
    std::cout << "hours: " << z2_hours.count() << '\n';
}

输出

hours: 2
seconds: 7200
hours: 1
seconds: 7158
hours: 1.98833

[编辑] 另请参阅

构造新的 duration
(公共成员函数) [编辑]