C++之運算符重載的實例(日期類實現(xiàn)方式)
C++日期類的實現(xiàn)與深度解析
在C++編程中,自定義數(shù)據(jù)類型是構(gòu)建復(fù)雜應(yīng)用的基礎(chǔ)。日期作為一個常用的數(shù)據(jù)類型,涉及到多種操作,如日期的加減、比較、計算間隔天數(shù)等。
一、代碼結(jié)構(gòu)概覽
我們實現(xiàn)的Date類包含了日期相關(guān)的核心功能,代碼分為頭文件Date.h和源文件Date.cpp兩部分。
頭文件負(fù)責(zé)類的聲明,定義類的成員函數(shù)接口和數(shù)據(jù)成員;源文件則實現(xiàn)這些成員函數(shù),完成具體的業(yè)務(wù)邏輯。
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;
// 全缺省的構(gòu)造函數(shù)
Date(int year = 1900, int month = 1, int day = 1);
// 拷貝構(gòu)造函數(shù)
Date(const Date& d);
// 賦值運算符重載
Date& operator=(const Date& d);
// 析構(gòu)函數(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];
}
// 全缺省構(gòu)造函數(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;
// 使用默認(rèn)值
_year = 1900;
_month = 1;
_day = 1;
}
else
{
_year = year;
_month = month;
_day = day;
}
}
// 拷貝構(gòu)造函數(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;
}
// 析構(gòu)函數(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,則直接計算當(dāng)前月剩余天數(shù)
days += max._day - min._day;
break;
}
else
{
// 計算當(dāng)前月的剩余天數(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ù),從基礎(chǔ)的日期創(chuàng)建、拷貝、賦值,到復(fù)雜的日期計算與比較,每個函數(shù)各司其職,共同完成日期類的功能。
二、關(guān)鍵函數(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),也允許常量對象調(diào)用。
2.2 構(gòu)造函數(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;
// 使用默認(rèn)值
_year = 1900;
_month = 1;
_day = 1;
}
else
{
_year = year;
_month = month;
_day = day;
}
}構(gòu)造函數(shù)用于初始化Date對象。在初始化前,對傳入的年份、月份和日期進行合法性檢查,若日期不合法,則將對象初始化為默認(rèn)日期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ū)分前置與后置,后置類型要在括號當(dāng)中加入int形參,與前置構(gòu)成重載;
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,則直接計算當(dāng)前月剩余天數(shù)
days += max._day - min._day;
break;
}
else
{
// 計算當(dāng)前月的剩余天數(shù)
days += GetMonthDay(min._year, min._month) - min._day + 1;
// 跳到下個月1號
min = nextMonth;
}
}
return days * flag;
}日期比較函數(shù)通過依次比較年份、月份和日期,判斷兩個日期的大小關(guān)系;operator-函數(shù)用于計算兩個日期之間的天數(shù)差,采用逐月計算的優(yōu)化算法,減少不必要的循環(huán)次數(shù),提高計算效率。
三、代碼優(yōu)化與注意事項
3.1 代碼優(yōu)化
- 成員函數(shù)添加
const修飾:將不修改對象狀態(tài)的成員函數(shù)聲明為const,如GetMonthDay、日期比較函數(shù)等,提高代碼的安全性和可讀性,同時允許常量對象調(diào)用這些函數(shù)。 - 日期差值計算優(yōu)化:在計算兩個日期差值時,采用逐月計算的方式,避免了每次只增加一天的低效循環(huán),大幅提升計算效率。
3.2 注意事項
- 日期合法性檢查:在構(gòu)造函數(shù)和其他涉及日期修改的函數(shù)中,要確保對日期的合法性進行嚴(yán)格檢查,防止出現(xiàn)無效日期。
- 運算符重載的一致性:在重載日期相關(guān)運算符時,要保證邏輯的一致性和正確性,例如
operator+和operator+=之間的關(guān)系,避免出現(xiàn)邏輯矛盾。 - 避免內(nèi)存泄漏:雖然
Date類中沒有動態(tài)內(nèi)存分配,但在更復(fù)雜的類設(shè)計中,析構(gòu)函數(shù)要正確釋放資源,防止內(nèi)存泄漏。
四、總結(jié)
通過實現(xiàn)Date類,運用了C++中類的設(shè)計、運算符重載、構(gòu)造函數(shù)、析構(gòu)函數(shù)等核心概念。日期類的實現(xiàn)不僅涉及到基本的數(shù)學(xué)計算,還需要處理各種邊界情況和邏輯判斷。
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
C++實現(xiàn)LeetCode(74.搜索一個二維矩陣)
這篇文章主要介紹了C++實現(xiàn)LeetCode(74.搜索一個二維矩陣),本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-07-07
C++實例分析組合數(shù)的計算與排列組合的產(chǎn)生
這篇文章主要介紹了C++組合數(shù)的計算與排列和組合無重集元素的產(chǎn)生,對計算算法感興趣的同學(xué),可以參考一下,理解其原理,并且試驗一下。2022-07-07
C++用read()和write()讀寫二進制文件的超詳細(xì)教程
二進制的文件肉眼我們是讀不懂的,如果通過二進制的讀寫操作就可以讀懂,下面這篇文章主要給大家介紹了關(guān)于C++用read()和write()讀寫二進制文件的相關(guān)資料,文中通過實例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-06-06
C語言詳細(xì)分析不同類型數(shù)據(jù)在內(nèi)存中的存儲
使用編程語言進行編程時,需要用到各種變量來存儲各種信息。變量保留的是它所存儲的值的內(nèi)存位置。這意味著,當(dāng)您創(chuàng)建一個變量時,就會在內(nèi)存中保留一些空間。您可能需要存儲各種數(shù)據(jù)類型的信息,操作系統(tǒng)會根據(jù)變量的數(shù)據(jù)類型,來分配內(nèi)存和決定在保留內(nèi)存中存儲什么2022-08-08
C++中對象的常引用、動態(tài)建立和釋放相關(guān)知識講解
這篇文章主要介紹了C++中對象的常引用、動態(tài)建立和釋放相關(guān)知識講解,是C++入門學(xué)習(xí)中的基礎(chǔ)知識,需要的朋友可以參考下2015-09-09

