定义的Date类中增加“>>”、“<<”的重载,实现日期的输入及输出。
时间: 2024-03-03 21:47:25 浏览: 23
好的,下面是实现Date类的输入输出重载的示例代码:
```cpp
#include <iostream>
using namespace std;
class Date {
public:
Date(int year = 1900, int month = 1, int day = 1) {
year_ = year;
month_ = month;
day_ = day;
}
friend ostream& operator<<(ostream& os, const Date& date);
friend istream& operator>>(istream& is, Date& date);
private:
int year_;
int month_;
int day_;
};
ostream& operator<<(ostream& os, const Date& date) {
os << date.year_ << "-" << date.month_ << "-" << date.day_;
return os;
}
istream& operator>>(istream& is, Date& date) {
char c;
is >> date.year_ >> c >> date.month_ >> c >> date.day_;
return is;
}
```
这里使用了友元函数实现了输入输出重载,`<<` 用于输出日期,`>>` 用于输入日期。在 `>>` 重载中,我们首先读入年月日,然后使用一个字符变量 `c` 读取并丢弃掉输入流中的分隔符。最后返回输入流。在 `<<` 重载中,我们直接将日期按照指定格式输出即可。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![ppt](https://img-home.csdnimg.cn/images/20210720083527.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)