当前位置:网站首页>Implementation of date class and its basic functions
Implementation of date class and its basic functions
2022-07-28 05:43:00 【zhengyawen666】
Catalog
One Get the number of days in the month
2 Overload of assignment operators
5 In front of ++ And post ++ In front of -- And post --
6 heavy load - Realize the subtraction of two dates and return the difference in days
One Get the number of days in the month
Static array method is used to get the month and days . Because the array subscript is from 0 At the beginning , In order to make the month correspond to the subscript one by one , open 13 individual int Array of sizes . But the subscript is 0 Place it in any location 0, Used for occupying . Then the corresponding days of the corresponding month .
If it's a leap year , Then the month of this year will be +1;
Because he is called frequently , So I write it inside the function , As an inline function to improve efficiency .
int GetMonthDay(int year, int month)
{
int monthday[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };
if (year % 400 == 0 || year % 4 == 0 && year % 100 != 0)
{
monthday[2] += 1;
}
return monthday[month];
}Two Constructors
1 Full default constructor
The full default constructor is actually when writing the constructor , Set the corresponding default value for month, year and day .
Date(int year = 1, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
}// Full default constructor 2 copy constructor
The copy constructor passes in the corresponding date class . Note that you must pass in references . Otherwise, infinite recursion will occur .
Date(Date const& date)
{
_year = date._year;
_month = date._month;
_day = date._day;
}// copy constructor 3、 ... and Destructor
Destructors of date classes are optional . Because the date class has no corresponding resources to clean up . But even so , We don't write , The compiler will also automatically generate a destructor . But this destructor doesn't need to do anything . But it was actually called .
~Date()
{
}// Destructor Four Operator overloading
1 > >= < <= == !=
Operator overloading , In fact, we only need to realize == and < perhaps == and > that will do . Because other operators are overloaded and reused, the written ones can be implemented . Such as the implementation <=, Then the logic is > The logic of is negative and satisfies ==.
bool operator==(const Date& date)const
{
return _year == date._year
&& _month == date._month
&& _day == date._day;
}
bool operator!=(const Date& date)const
{
return !(*this == date);
}
bool operator>(const Date& date)const
{
if (_year > date._year)
{
return true;
}
else if (_year == date._year && _month > date._month)
{
return true;
}
else if (_year == date._year && _month == date._month && _day > date._day)
{
return true;
}
else
{
return false;
}
}
bool operator>=(const Date& date)const
{
return(*this > date && *this == date);
}
bool operator<(const Date& date)const
{
return !(*this >= date);
}
bool operator<=(const Date& date)const
{
return (*this < date && *this == date);
}2 Overload of assignment operators
Overloaded assignment operators can be passed by reference , And because there is no need to modify the incoming parameters , So you can use const To modify . Because the return is overloaded by assignment *this. Will not be destroyed . Therefore, you can also use reference return to improve efficiency .
Date& operator=(const Date& date)
{
_year = date._year;
_month = date._month;
_day = date._day;
return *this;
}// Assignment overload 3 += And +
①+= The idea is to carry . First of all, add it all to the day , Carry again . The rules of carry : If the date is illegal , For example, the day is greater than the maximum number of days in the month , Then you need to carry up the month . If the month is also greater than the largest month of the year . Then carry forward to the year .
Pay attention to is , When the month is rounded to the year , At the same time, the month will also be set to 1.
Date&operator+=(int day)
{
if (day < 0)
{
return *this -= -day;
}
_day += day;
while(_day > GetMonthDay(_year, _month))
{
_day -= GetMonthDay(_year, _month);
_month+=1;
if (_month > 12)
{
_year += 1;
_month = 1;
}
}
return *this;
}②+
because + Words , It won't be right *this Generate modification , Therefore, you need to use a temporary variable to complete the above operations , And return this temporary variable .
Other code implementations can also be reused directly
Date operator+(int day)
{
Date ret(*this);
ret += day;
return ret;
}4 -= And -
①-=
And += On the contrary . But here's the thing , You need to judge whether the month is legal , Add the borrowed days of the previous month to the current month . otherwise , If January is illegal , Borrow position , What you borrow is 0 Days of month .
Date& operator-=(int day)
{
if (day < 0)
{
return *this += -day;
}
_day -= day;
while (_day<1)
{
_month -= 1;
if (_month < 1)
{
_year -= 1;
_month = 12;
}
_day += GetMonthDay(_year, _month);// Judge first Because I borrowed it for a year If you don't judge 1 If the number of days in the month is negative, the debit cannot be added at this time Also need to borrow from Nian
}
return *this;
}②-
Just reuse as above .
Date operator-(int day)
{
Date ret(*this);
return ret -= day;
}Why -= and += To reuse - and +?
If it comes the other way , You need to implement many copy constructions , It reduces efficiency .
5 In front of ++ And post ++ In front of -- And post --
① In front of ++
In front of ++ The return is ++ The value of the former , And it will also be modified . Therefore, you need to save with temporary variables ++ The value of the former , And return this temporary variable . Therefore, the return value cannot be referenced . In front of ++ Parameter list with int It's OK not to pass on the parameters , Mainly for the sake of post ++ Phase differentiation
Date operator++(int)
{
Date ret(*this);
*this += 1;
return ret;
}② After ++
After ++ return ++ The value after , So just go straight back .
Date& operator++()
{
return *this +=1;
}In front of -- And post -- The logic is similar to the above implementation .
Don't elaborate too much .
Date& operator--()
{
return *this -= 1;
}
Date operator--(int)
{
Date ret(*this);
*this -= 1;
return ret;
}6 heavy load - Realize the subtraction of two dates and return the difference in days
Ideas : It is mainly the date to get the smaller number of days , Use a counter to calculate the difference in days between the two .
flag To achieve positive and negative . By default, the first date type is larger than the second date type .flag Being positive . But if contrary to the conjecture , Size date and flag All need to be reset .
int operator-( const Date&date)const
{
int flag = 1;
Date min = date;
Date max = *this;
if (*this >date)
{
max = date;
min = *this;
flag = -1;
}
int count = 0;
while (min != max)
{
count++;
min++;
}
return count * flag;
}
边栏推荐
- regular expression
- BigDecimal rounds and retains two decimal places
- 论文写作用词
- Video twins: the starting point of informatization upgrading of smart Parks
- Deep learning medical image model reproduction
- Openjudge: perpetual calendar
- Feignclient calls the get method and reports an error resultvo{result= unknown exception. Exception details: request method 'post' not supported
- Mabtis(一)框架的基本使用
- 对极大似然估计、梯度下降、线性回归、逻辑回归的理解
- Pytorch uses hook to get feature map
猜你喜欢
随机推荐
标准C语言总结1
regular expression
repackag failed: Unable to find main class
Digital twin technology creates visual application of smart mine
标准C语言学习总结8
Methods of gflops and total params of pytorch calculation model
openjudge:字符串最大跨距
Video twins: the starting point of informatization upgrading of smart Parks
[MySQL] solve the problem of MySQL time zone and 8-hour difference in database time
Fusiongan code learning (I)
Openjudge: find all substring positions
冶金物理化学复习 -- 金属电沉积过程中的阴极极化,超电势以及阳极和阳极过程
Feignclient calls the get method and reports an error resultvo{result= unknown exception. Exception details: request method 'post' not supported
使用深度学习训练图像时,图像太大进行切块训练预测
openjudge:找出全部子串位置
Delete specific elements in order table OJ
Openjudge: judge whether the string is palindrome
冶金物理化学复习 --- 冶金反应动力学基础与多相反应动力学特征
[singleton mode] thread safety of lazy mode
Invalid bound statement (not found): com.exam.mapper.UserMapper.findbyid



![[idea plug-in artifact] teaches you how to set all attributes in an entity class with one click of idea](/img/d6/4e69480c5ad5040ee48941ca0fcb37.png)




