C++ day2

该代码示例展示了如何在C++中定义一个矩形类,包括初始化、设置宽度和高度的方法,以及显示周长和面积的成员函数。用户可以通过输入修改矩形的尺寸。

思维导图

封装一个矩形类

#include <iostream>

using namespace std;

class Rect
{
private:
    int height;
    int width;

public:
    void init(int w,int h)
    {
        width = w;
        height = h;
    }
    void set_w(int w)
    {
        width = w;
    }

    void set_h(int h)
    {
        height = h;
    }

    void show()
    {

        cout << "周长为:" << (width+height)*2 << endl;
        cout << "面积为:" << width * height << endl;

    }

};


int main()
{
    Rect s1;
    s1.init(10,5);
    s1.show();
    int w,h;
    cout << "请输入更改的宽度:";
    cin >> w ;
    s1.set_w(w);
    cout << "请输入要更改的长度:";
    cin >> h;
    s1.set_h(h);
    s1.show();
    return 0;
}

C++ 标准库中,并没有名为 `day_iterator` 的参数或类型。可能用户提到的 `day_iterator` 是对某些迭代器(iterator)概念的一种误解,或者是特定库中的自定义类型。 在标准库中,与日期相关的功能主要出现在 `<chrono>` 头文件中,而 C++20 引入了更完整的日期和时间处理功能,包括 `std::chrono::year_month_day` 和相关的日期操作。然而,C++ 标准库并未提供专门的 `day_iterator` 类型用于遍历日期。 如果需要实现类似功能,可以自定义一个日期迭代器,例如使用 `std::chrono` 中的日期操作来实现逐日递增的迭代器[^1]。 以下是一个简单的示例,展示如何使用 C++20 的 `<chrono>` 库来实现一个“按天递增”的迭代器: ```cpp #include <iostream> #include <chrono> namespace chrono = std::chrono; class day_iterator { private: chrono::sys_days _current; public: using iterator_category = std::forward_iterator_tag; using value_type = chrono::sys_days; using difference_type = std::ptrdiff_t; using pointer = const chrono::sys_days*; using reference = const chrono::sys_days&; explicit day_iterator(chrono::sys_days start) : _current(start) {} reference operator*() const { return _current; } pointer operator->() const { return &_current; } day_iterator& operator++() { _current += chrono::days(1); return *this; } day_iterator operator++(int) { day_iterator tmp = *this; ++(*this); return tmp; } bool operator==(const day_iterator& other) const { return _current == other._current; } bool operator!=(const day_iterator& other) const { return !(*this == other); } }; int main() { // 从 2023-10-01 开始 auto start_date = chrono::sys_days{chrono::year(2023)/10/1}; auto end_date = chrono::sys_days{chrono::year(2023)/10/6}; day_iterator begin(start_date); day_iterator end(end_date); for (auto it = begin; it != end; ++it) { auto ymd = chrono::year_month_day(*it); std::cout << static_cast<std::string>(ymd) << std::endl; } return 0; } ``` 该程序输出如下内容: ``` 2023-10-01 2023-10-02 2023-10-03 2023-10-04 2023-10-05 ``` 上述代码展示了如何创建一个前向迭代器,用于遍历从起始日期到结束日期之间的每一天。这个自定义的 `day_iterator` 实现了基本的迭代器接口,支持前置递增、解引用和比较操作。 ### 示例说明 - 使用 `std::chrono::sys_days` 表示系统时钟上的日期。 - 每次调用 `operator++()` 都会将当前日期增加一天。 - 迭代器支持与标准算法兼容的接口,例如 `begin()` 和 `end()`。 ### 注意事项 - 该实现是前向迭代器(`std::forward_iterator_tag`),不支持双向或随机访问。 - 如果未使用 C++20 或 `<chrono>` 的日历功能,可能需要依赖第三方库如 Boost.Date_Time 来实现类似的日期迭代功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值