C++之運算符重載的實例(日期類實現(xiàn)方式)
C++日期類的實現(xiàn)與深度解析
在C++編程中,自定義數(shù)據(jù)類型是構建復雜應用的基礎。日期作為一個常用的數(shù)據(jù)類型,涉及到多種操作,如日期的加減、比較、計算間隔天數(shù)等。
一、代碼結構概覽
我們實現(xiàn)的Date
類包含了日期相關的核心功能,代碼分為頭文件Date.h
和源文件Date.cpp
兩部分。
頭文件負責類的聲明,定義類的成員函數(shù)接口和數(shù)據(jù)成員;源文件則實現(xiàn)這些成員函數(shù),完成具體的業(yè)務邏輯。
1.1 頭文件 Date.h
// Date.h #pragma once #include <iostream> #include <assert.h> using namespace std; class Date { public: // 獲取某年某月的天數(shù) int GetMonthDay(int year, int month) const; // 全缺省的構造函數(shù) Date(int year = 1900, int month = 1, int day = 1); // 拷貝構造函數(shù) Date(const Date& d); // 賦值運算符重載 Date& operator=(const Date& d); // 析構函數(shù) ~Date(); // 日期+=天數(shù) Date& operator+=(int day); // 日期+天數(shù) Date operator+(int day) const; // 日期-天數(shù) Date operator-(int day) const; // 日期-=天數(shù) Date& operator-=(int day); // 前置++ Date& operator++(); // 后置++ Date operator++(int); // 后置-- Date operator--(int); // 前置-- Date& operator--(); // >運算符重載 bool operator>(const Date& d) const; // ==運算符重載 bool operator==(const Date& d) const; // >=運算符重載 bool operator >= (const Date& d) const; // <運算符重載 bool operator < (const Date& d) const; // <=運算符重載 bool operator <= (const Date& d) const; // !=運算符重載 bool operator != (const Date& d) const; // 日期-日期 返回天數(shù) int operator-(const Date& d) const; // 輸出日期 void Print() const; private: int _year; int _month; int _day; };
頭文件中定義了Date
類,包含私有成員變量_year
、_month
、_day
,用于存儲日期的年、月、日信息;同時聲明了一系列成員函數(shù),涵蓋日期計算、比較、賦值等操作。
1.2 源文件 Date.cpp
// Date.cpp #define _CRT_SECURE_NO_WARNINGS 1 #include "Date.h" // 實現(xiàn)獲取某年某月天數(shù)的函數(shù) int Date::GetMonthDay(int year, int month) const { assert(month > 0 && month < 13); static int arr[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 }; if (month == 2 && ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)) return 29; return arr[month]; } // 全缺省構造函數(shù),同時檢查日期合法性 Date::Date(int year, int month, int day) { // 檢查日期合法性 if (year < 0 || month < 1 || month > 12 || day < 1 || day > GetMonthDay(year, month)) { cout << "Invalid date: " << year << "-" << month << "-" << day << endl; // 使用默認值 _year = 1900; _month = 1; _day = 1; } else { _year = year; _month = month; _day = day; } } // 拷貝構造函數(shù) Date::Date(const Date& d) { _year = d._year; _month = d._month; _day = d._day; } // 賦值運算符重載 Date& Date::operator=(const Date& d) { if (this != &d) { _year = d._year; _month = d._month; _day = d._day; } return *this; } // 析構函數(shù),無需顯式將成員置零 Date::~Date() { // 不需要在這里將成員置零 } // 日期加上指定天數(shù) Date& Date::operator+=(int day) { if (day < 0) { return *this -= -day; } _day += day; while (_day > GetMonthDay(_year, _month)) { _day -= GetMonthDay(_year, _month); _month++; if (_month == 13) { _month = 1; _year++; } } return *this; } // 日期加上指定天數(shù),返回新的日期對象 Date Date::operator+(int day) const { Date tmp = *this; tmp += day; return tmp; } // 日期減去指定天數(shù) Date& Date::operator-=(int day) { if (day < 0) { return *this += -day; } _day -= day; while (_day <= 0) { _month--; if (_month == 0) { _month = 12; _year--; } _day += GetMonthDay(_year, _month); } return *this; } // 日期減去指定天數(shù),返回新的日期對象 Date Date::operator-(int day) const { Date tmp = *this; tmp -= day; return tmp; } // 前置++操作 Date& Date::operator++() { *this += 1; return *this; } // 后置++操作 Date Date::operator++(int) { Date tmp(*this); *this += 1; return tmp; } // 后置--操作 Date Date::operator--(int) { Date tmp(*this); *this -= 1; return tmp; } // 前置--操作 Date& Date::operator--() { *this -= 1; return *this; } // 比較兩個日期大小 bool Date::operator>(const Date& d) const { if (_year > d._year) return true; else if (_year == d._year) { if (_month > d._month) return true; else if (_month == d._month) return _day > d._day; } return false; } // 判斷兩個日期是否相等 bool Date::operator==(const Date& d) const { return _year == d._year && _month == d._month && _day == d._day; } // 判斷一個日期是否大于等于另一個日期 bool Date::operator >= (const Date& d) const { return *this > d || *this == d; } // 判斷一個日期是否小于另一個日期 bool Date::operator < (const Date& d) const { return !(*this >= d); } // 判斷一個日期是否小于等于另一個日期 bool Date::operator <= (const Date& d) const { return !(*this > d); } // 判斷兩個日期是否不相等 bool Date::operator != (const Date& d) const { return !(*this == d); } // 計算兩個日期之間的天數(shù)差 int Date::operator-(const Date& d) const { Date min = *this; Date max = d; int flag = 1; if (min > max) { min = d; max = *this; flag = -1; } int days = 0; // 優(yōu)化算法:逐月計算天數(shù)差 while (min < max) { // 計算下個月1號的日期 Date nextMonth(min._year, min._month + 1, 1); if (nextMonth > max) { // 如果下個月超過了max,則直接計算當前月剩余天數(shù) days += max._day - min._day; break; } else { // 計算當前月的剩余天數(shù) days += GetMonthDay(min._year, min._month) - min._day + 1; // 跳到下個月1號 min = nextMonth; } } return days * flag; } // 輸出日期 void Date::Print() const { cout << _year << "-" << _month << "-" << _day << endl; }
源文件中具體實現(xiàn)了頭文件聲明的各個成員函數(shù),從基礎的日期創(chuàng)建、拷貝、賦值,到復雜的日期計算與比較,每個函數(shù)各司其職,共同完成日期類的功能。
二、關鍵函數(shù)實現(xiàn)解析
2.1 獲取某月天數(shù)函數(shù) GetMonthDay
int Date::GetMonthDay(int year, int month) const { assert(month > 0 && month < 13); static int arr[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 }; if (month == 2 && ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)) return 29; return arr[month]; }
該函數(shù)用于獲取指定年份和月份的天數(shù)。通過一個靜態(tài)數(shù)組arr
存儲常規(guī)月份的天數(shù),并根據(jù)閏年規(guī)則(能被4整除但不能被100整除,或者能被400整除)判斷2月的天數(shù)。
函數(shù)聲明為const
成員函數(shù),表明不會修改對象的狀態(tài),也允許常量對象調用。
2.2 構造函數(shù) Date
Date::Date(int year, int month, int day) { // 檢查日期合法性 if (year < 0 || month < 1 || month > 12 || day < 1 || day > GetMonthDay(year, month)) { cout << "Invalid date: " << year << "-" << month << "-" << day << endl; // 使用默認值 _year = 1900; _month = 1; _day = 1; } else { _year = year; _month = month; _day = day; } }
構造函數(shù)用于初始化Date
對象。在初始化前,對傳入的年份、月份和日期進行合法性檢查,若日期不合法,則將對象初始化為默認日期1900-01-01
,保證對象的有效性。
2.3 日期加減法運算
在這里為了減少類類型的拷貝,節(jié)約資源,通常先實現(xiàn)+= 或 -=;
Date& Date::operator+=(int day) { if (day < 0) { return *this -= -day; } _day += day; while (_day > GetMonthDay(_year, _month)) { _day -= GetMonthDay(_year, _month); _month++; if (_month == 13) { _month = 1; _year++; } } return *this; } Date Date::operator+(int day) const { Date tmp = *this; tmp += day; return tmp; }
operator+=
函數(shù)實現(xiàn)了日期加上指定天數(shù)的功能,通過循環(huán)處理跨月、跨年的情況;operator+
函數(shù)則基于operator+=
,返回一個新的日期對象,保持原對象不變。
類似地,operator-=
和operator-
函數(shù)實現(xiàn)了日期減法操作。
2.4 前置與后置自增/自減操作
為區(qū)分前置與后置,后置類型要在括號當中加入int形參,與前置構成重載;
Date& Date::operator++() { *this += 1; return *this; } Date Date::operator++(int) { Date tmp(*this); *this += 1; return tmp; }
前置自增operator++
先對日期進行加1操作,再返回修改后的對象;后置自增operator++(int)
通過創(chuàng)建臨時對象保存原始狀態(tài),對原對象進行加1操作后,返回臨時對象,保證后置自增“先使用,后修改”的語義。自減操作operator--
和operator--(int)
的實現(xiàn)原理與之類似。
2.5 日期比較與差值計算
在自我實現(xiàn)日期比較時,只需實現(xiàn)一個>或<,加上一個=,其余的都可以用這兩個來實現(xiàn)。
bool Date::operator>(const Date& d) const { if (_year > d._year) return true; else if (_year == d._year) { if (_month > d._month) return true; else if (_month == d._month) return _day > d._day; } return false; } int Date::operator-(const Date& d) const { Date min = *this; Date max = d; int flag = 1; if (min > max) { min = d; max = *this; flag = -1; } int days = 0; // 優(yōu)化算法:逐月計算天數(shù)差 while (min < max) { // 計算下個月1號的日期 Date nextMonth(min._year, min._month + 1, 1); if (nextMonth > max) { // 如果下個月超過了max,則直接計算當前月剩余天數(shù) days += max._day - min._day; break; } else { // 計算當前月的剩余天數(shù) days += GetMonthDay(min._year, min._month) - min._day + 1; // 跳到下個月1號 min = nextMonth; } } return days * flag; }
日期比較函數(shù)通過依次比較年份、月份和日期,判斷兩個日期的大小關系;operator-
函數(shù)用于計算兩個日期之間的天數(shù)差,采用逐月計算的優(yōu)化算法,減少不必要的循環(huán)次數(shù),提高計算效率。
三、代碼優(yōu)化與注意事項
3.1 代碼優(yōu)化
- 成員函數(shù)添加
const
修飾:將不修改對象狀態(tài)的成員函數(shù)聲明為const
,如GetMonthDay
、日期比較函數(shù)等,提高代碼的安全性和可讀性,同時允許常量對象調用這些函數(shù)。 - 日期差值計算優(yōu)化:在計算兩個日期差值時,采用逐月計算的方式,避免了每次只增加一天的低效循環(huán),大幅提升計算效率。
3.2 注意事項
- 日期合法性檢查:在構造函數(shù)和其他涉及日期修改的函數(shù)中,要確保對日期的合法性進行嚴格檢查,防止出現(xiàn)無效日期。
- 運算符重載的一致性:在重載日期相關運算符時,要保證邏輯的一致性和正確性,例如
operator+
和operator+=
之間的關系,避免出現(xiàn)邏輯矛盾。 - 避免內存泄漏:雖然
Date
類中沒有動態(tài)內存分配,但在更復雜的類設計中,析構函數(shù)要正確釋放資源,防止內存泄漏。
四、總結
通過實現(xiàn)Date
類,運用了C++中類的設計、運算符重載、構造函數(shù)、析構函數(shù)等核心概念。日期類的實現(xiàn)不僅涉及到基本的數(shù)學計算,還需要處理各種邊界情況和邏輯判斷。
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
C語言實現(xiàn)學生信息管理系統(tǒng)(文件版)
這篇文章主要為大家詳細介紹了C語言實現(xiàn)學生信息管理系統(tǒng),文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2020-07-07