为日期定义一个类。属性为年、月、日。要求重载 “++”、“--”(自增和自减运算符要求分前置和后置)、“<<”、“>>”等运算符,实现今天日期的输入输出、明天、昨天的日期求解和输出。用C++多文件实现
时间: 2023-11-05 21:11:44 浏览: 222
以下是实现代码,分为Date.h和Date.cpp两个文件:
### Date.h
```cpp
#pragma once
#include <iostream>
class Date {
public:
Date(int y, int m, int d) : year(y), month(m), day(d) {}
friend std::ostream& operator<<(std::ostream& os, const Date& date);
friend std::istream& operator>>(std::istream& is, Date& date);
Date operator++(); // 前置自增运算符
Date operator++(int); // 后置自增运算符
Date operator--(); // 前置自减运算符
Date operator--(int); // 后置自减运算符
private:
int year;
int month;
int day;
};
```
### Date.cpp
```cpp
#include "Date.h"
#include <iomanip>
std::ostream& operator<<(std::ostream& os, const Date& date) {
os << date.year << "-" << std::setw(2) << std::setfill('0') << date.month << "-" << std::setw(2) << std::setfill('0') << date.day;
return os;
}
std::istream& operator>>(std::istream& is, Date& date) {
char delimiter;
is >> date.year >> delimiter >> date.month >> delimiter >> date.day;
return is;
}
Date Date::operator++() {
if (day == 31 && month == 12) {
year++;
month = day = 1;
} else if (day == 31) {
month++;
day = 1;
} else {
day++;
}
return *this;
}
Date Date::operator++(int) {
Date temp = *this;
++(*this);
return temp;
}
Date Date::operator--() {
if (day == 1 && month == 1) {
year--;
month = day = 31;
} else if (day == 1) {
month--;
day = 31;
} else {
day--;
}
return *this;
}
Date Date::operator--(int) {
Date temp = *this;
--(*this);
return temp;
}
```
使用示例:
```cpp
#include "Date.h"
#include <iostream>
int main() {
Date today(2021, 9, 1);
std::cout << "Today is " << today << std::endl;
Date tomorrow = today++;
std::cout << "Tomorrow is " << tomorrow << std::endl;
Date yesterday = today--;
std::cout << "Yesterday was " << yesterday << std::endl;
std::cout << "Enter a date (YYYY-MM-DD): ";
std::cin >> today;
std::cout << "You entered " << today << std::endl;
return 0;
}
```
阅读全文