c++类与对象运算符重载的编程题
时间: 2025-01-29 11:10:29 浏览: 23
C++ 中类与对象运算符重载编程练习
题目描述
设计一个 Date
类,用于表示日期。该类应支持以下功能:
- 构造函数初始化年、月、日。
- 提供输入和输出流的重载运算符 << 和 >> ,以便能够方便地读取和显示日期。
- 实现加法运算符 + 来增加天数到当前日期上。
- 实现比较运算符 == 和 != 来判断两个日期是否相同。
为了简化问题,假设每个月都有 30 天,并忽略闰年的存在[^1]。
完整代码实现
#include <iostream>
using namespace std;
class Date {
private:
int year;
int month;
int day;
public:
// 默认构造函数
Date() : year(0), month(0), day(0) {}
// 参数化构造函数
Date(int y, int m, int d) : year(y), month(m), day(d) {}
// 加法运算符重载
friend Date operator+(const Date& date, const int days);
// 流插入运算符重载
friend ostream& operator<<(ostream& os, const Date& date);
// 流提取运算符重载
friend istream& operator>>(istream& is, Date& date);
// 比较相等运算符重载
bool operator==(const Date& other) const {
return (year == other.year && month == other.month && day == other.day);
}
// 不等于运算符重载
bool operator!=(const Date& other) const {
return !(*this == other);
}
};
// 加法运算符的具体实现
Date operator+(const Date& date, const int days) {
Date new_date(date.year, date.month, date.day);
while(days--) {
++new_date.day;
if(new_date.day > 30){
new_date.day -= 30;
++new_date.month;
if(new_date.month > 12){
new_date.month -= 12;
++new_date.year;
}
}
}
return new_date;
}
// 输出流运算符具体实现
ostream& operator<<(ostream& os, const Date& date) {
os << date.year << "-" << date.month << "-" << date.day;
return os;
}
// 输入流运算符具体实现
istream& operator>>(istream& is, Date& date) {
char ch1, ch2; // For reading '-' characters between numbers.
is >> date.year >> ch1 >> date.month >> ch2 >> date.day;
return is;
}
此段代码展示了如何在一个简单的 Date
类中实现基本的运算符重载[^2]。通过这种方式,可以更直观地处理日期之间的各种关系和操作。
相关推荐


















