当前位置:网站首页>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;
}
边栏推荐
- ResNet结构对比
- Example of main diagram of paper model
- 深度学习医学图像模型复现
- You must configure either the server or JDBC driver (via the ‘serverTimezone)
- Openjudge: upper and lower case letters are interchanged
- pytorch安装----CPU版的
- 日期类及其基本功能的实现
- Centos7 install MySQL 5.7
- When using \hl for highlighting, latex always reports an error when encountering a reference, showing that there are fewer or more parentheses
- 冶金物理化学复习 --- 复杂反应的速率方程
猜你喜欢

树莓派串口配置

Invalid bound statement (not found): com.exam.mapper.UserMapper.findbyid

冶金物理化学复习 --- 液 - 液相反应动力学

顺序表oj题目

Leetcode 随即链表的深拷贝

Sequence table OJ topic

树莓派WIFI一键连接配置

Operation and use of collection framework

Advanced multithreading: the role and implementation principle of volatile

Personal summary of restful interface use
随机推荐
使用深度学习训练图像时,图像太大进行切块训练预测
openjudge:找第一个只出现一次的字符
Custom JSON return data
C语言回顾(修饰词篇)
List < long >, list < integer > convert each other
对极大似然估计、梯度下降、线性回归、逻辑回归的理解
openjudge:大小写字母互换
Methods of gflops and total params of pytorch calculation model
Openjudge: upper and lower case letters are interchanged
Problems encountered when the registry service Eureka switches to nocas
Review of Metallurgical Physical Chemistry - gas liquid phase reaction kinetics
c语言:通过一个例子来认识函数栈帧的创建和销毁讲解
When SQL queries the list, the data is inconsistent twice, and limit is automatically added
论文写作用词
Deep learning medical image model reproduction
[MySQL] solve the problem of MySQL time zone and 8-hour difference in database time
NRF51822 回顾总结
GET与POST区别
顺序表oj之合并两个有序数组
Simpledateformat thread unsafe and datetimeformatter thread safe