C++ Date类运算符重载
作者:野牛程序员:2024-01-03 20:45:47 C++阅读 2665
Date类的运算符重载可以在C++中执行日期对象的各种操作。以下是一个简单的示例,演示如何在Date类中重载一些基本的运算符,包括加法、减法和比较运算符。
#include <iostream>
class Date {
public:
int day, month, year;
// 构造函数
Date(int d, int m, int y) : day(d), month(m), year(y) {}
// 重载加法运算符
Date operator+(const Date& other) const {
Date result = *this;
result.day += other.day;
result.month += other.month;
result.year += other.year;
// 处理进位
if (result.day > 31) {
result.day -= 31;
result.month++;
}
if (result.month > 12) {
result.month -= 12;
result.year++;
}
return result;
}
// 重载减法运算符
Date operator-(const Date& other) const {
Date result = *this;
result.day -= other.day;
result.month -= other.month;
result.year -= other.year;
// 处理借位
if (result.day < 1) {
result.day += 31;
result.month--;
}
if (result.month < 1) {
result.month += 12;
result.year--;
}
return result;
}
// 重载比较运算符
bool operator==(const Date& other) const {
return (day == other.day) && (month == other.month) && (year == other.year);
}
bool operator!=(const Date& other) const {
return !(*this == other);
}
};
int main() {
// 创建两个日期对象
Date date1(10, 3, 2022);
Date date2(5, 2, 2023);
// 使用重载的加法运算符
Date resultAdd = date1 + date2;
std::cout << "Date after addition: " << resultAdd.day << "/" << resultAdd.month << "/" << resultAdd.year << std::endl;
// 使用重载的减法运算符
Date resultSub = date1 - date2;
std::cout << "Date after subtraction: " << resultSub.day << "/" << resultSub.month << "/" << resultSub.year << std::endl;
// 使用重载的比较运算符
std::cout << "Are the dates equal? " << (date1 == date2 ? "Yes" : "No") << std::endl;
return 0;
}此示例仅包含了基本的加法、减法和比较运算符重载。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

