当前位置:网站首页>Implementation of date class
Implementation of date class
2022-07-01 00:54:00 【Hundred words lingdu】
Implementation of date class
Implementation of date class
Date.h
#pragma once
#include<iostream>
#include<assert.h>
using std::cout;
using std::cin;
using std::endl;
class Date
{
public:
void Print();
//1
//Date(const Date& d)
//{
// _year = d._year;
// _month = d._month;
// _day = d._day;
//}
//2
//Date& operator=(const Date& d)
//{
// if (this != &d)
// {
// _year = d._year;
// _month = d._month;
// _day = d._day;
// }
// return *this;
//}
// Judgement of leap year
bool LeapYear(int year)
{
if ((year % 4 == 0) && (year % 100 != 0))
return true;
if (year % 400 == 0)
return true;
return false;
}
// Get the number of days in any month
int GetMonthDay(int year, int month)
{
assert(year >= 0 && month > 0 && month < 13);
const static int day[13] = {
0,31,28,31,30,31,30,31,31,30,31,30,31 };
if (LeapYear(year) && month == 2)
return 29;
return day[month];
}
// Constructor for initialization
Date(int year=1 , int month=1 , int day=1 )
{
// Judge the legitimacy of time
assert(year >= 1 && month >= 1 && month <= 12 && day >= 1 && day <= GetMonthDay(year, month));
_year = year;
_month = month;
_day = day;
}
Date operator+(int day);
Date operator-(int day);
int operator-(Date& d);
// date += Days
Date& operator+=(int day);
// date -= Days
Date& operator-=(int day);
// In front of ++
Date& operator++();
// After ++
Date operator++(int);
// After --
Date operator--(int);
// In front of --
Date& operator--();
// > Operator overloading
bool operator>(const Date& d);
// == Operator overloading
bool operator==(const Date& d);
// >= Operator overloading
bool operator>= (const Date& d)
{
return (*this > d || *this == d);
}
// < Operator overloading
bool operator<(const Date& d)
{
return !(*this >= d);
}
// <= Operator overloading
bool operator <= (const Date& d)
{
return !(*this > d);
}
// != Operator overloading
bool operator != (const Date& d)
{
return !(*this == d);
}
private:
int _year;
int _month;
int _day;
};
//1
copy constructor , stay Date Class , Don't write , But if you want to write , Pay attention to parameter application const modification ( Because if it is Date d2=d1+10; This situation , among d1+10 Calling the addition overloaded function returns the value , It's actually d1+10 Copy to temporary variable , Temporary variables are copied to d2, Temporary variables have constant properties , So parameters need to use const modification )
//2
Assignment overloaded function , stay Date Class , Don't write , But if you want to write , Pay attention to parameter application const modification ( And 1 Empathy )
Date.cpp
#define _CRT_SECURE_NO_WARNINGS 1
#include"Date.h"
void Date::Print()
{
cout << _year << "-" << _month << "-" << _day << endl;
}
// date += Days
Date& Date::operator+=(int day)
{
//1
if (day < 0)
return *this -= -day;
//2
_day += day;
while (_day > GetMonthDay(_year, _month))
{
_day -= GetMonthDay(_year, _month);
_month++;
if (_month > 12)
{
_year++;
_month = 1;
}
}
//3
return *this;
}
// date -= Days
Date& Date::operator-=(int day)
{
//4
if (day < 0)
return *this += -day;
_day -= day;
while (_day <= 0)
{
_day += GetMonthDay(_year, _month);
_month--;
if (_month <= 0)
{
_month = 12;
_year--;
}
}
return *this;
}
//+ Days
Date Date:: operator+(int day)
{
//5
Date tmp(*this);
//6
tmp += day;
return tmp;
}
//- Days
Date Date::operator-(int day)
{
//7
Date tmp(*this);
tmp -= day;
return tmp;
}
//- date
int Date::operator-(Date& d)
{
//8
int flag = 1;
Date max(*this);
Date min(d);
if (*this < d)
{
min = *this;
max = d;
flag = -1;
}
int n = 0;
while (min != max)
{
min++;
n++;
}
return n * flag;
}
// In front of ++
Date& Date::operator++()
{
//9
(*this) += 1;
return *this;
}
// After ++
Date Date::operator++(int)
{
//10
Date tmp(*this);
(*this) += 1;
return tmp;
}
// After --
Date Date::operator--(int)
{
//11
Date tmp(*this);
(*this) -= 1;
return tmp;
}
// In front of --
Date& Date::operator--()
{
//12
(*this) -= 1;
return *this;
}
// > Operator overloading
bool Date::operator>(const Date& d)
{
if ((_year > d._year) || (_year == d._year && _month > d._month) || (_year == d._year && _month == d._month && _day > d._day))
return true;
return false;
}
// == Operator overloading
bool Date::operator==(const Date& d)
{
if ((_year == d._year) && (_month == d._month) && (_day == d._day))
return true;
return false;
}
//1
stay += in , If day It's a negative number , Equivalent to -= Positive numbers
//2
day>=0, take day Add... First *this Of _day On , Do a cycle ,
Judge whether the number of days exceeds the number of days in the current month , If more than , take *this._day Subtract the number of days in the current month ,*this._month++, Then judge whether the month exceeds 12, If more than ,*this._day=1,*this._year++.
until *this._day legal , The loop ends .
//3
+= Overloaded functions return by reference , because return *this, Because outside this function domain ,this The space pointed to by the pointer still exists , So you can return by reference ( Reference returns relative to value returns , No need to copy ( Call the copy constructor ), More efficient )
//4
-= And += Empathy
//5
- Days , Need assurance *this The value of does not change
//6
+ Days overload function , Use +=( Don't have to implement +, and += Is a reference that returns , More efficient )
//7
- Days and + The same goes for days
//8
- date
Set up a flag Judge *this And d The difference between positive and negative days , Two Date class ,max,min,max Larger ,min For the smaller , Set up n Days , A cycle ,min++,n++ until min and max equal , According to flag Return days .
//9
stay ++ Use in +=( No more ++), In front of ++ Is to return +1 The value after , return *this, Use a reference to return
//10
To avoid ambiguity when calling functions , After ++ Overloaded function arguments require int placeholder , After ++ Is to return +1 Previous value , return tmp, Use value return
//11
And post -- Empathy
//12
And pre -- Empathy
test.cpp
#define _CRT_SECURE_NO_WARNINGS 1
#include"Date.h"
void TestDate1()
{
Date d1(2022, 5, 18);
Date d2(2023, 3, 20);
Date d3(2023, 3, 20);
cout << (d1 < d2) << endl;
cout << (d1 > d2) << endl;
cout << (d1 == d3) << endl;
cout << (d2 <= d3) << endl;
cout << (d2 == d3) << endl;
}
void TestDate2()
{
Date d1(2022, 5, 18);
Date d2 = d1 + 15;// Copy construction is equivalent to Date d2(d1+15);
Date d3;
d3 = d1 + 15;// Assignment overload
d2.Print();
d1.Print();
d1 += 15;
d1.Print();
}
void TestDate3()
{
Date d1(2022, 5, 18);
Date d2 = d1 - 30;
d2.Print();
d1 -= 30;
d1.Print();
Date d3(2022, 5, 18);
d3 += 10000;
d3.Print();
d3 -= 10000;
d3.Print();
}
void TestDate4()
{
Date d1(2022, 5, 18);
d1 -= -100;
d1.Print();
d1 += -100;
d1.Print();
Date d2(2022, 5, 18);
Date ret1 = ++d2; // d2.operator++()
ret1.Print();
d2.Print();
Date ret2 = d2++; // d2.operator++(0)
ret2.Print();
d2.Print();
}
void TestDate5()
{
Date d1(2022, 5, 18);
Date d2(2020, 2, 4);
cout << (d1 - d2) << endl;
cout << (d2 - d1) << endl;
}
void Func(Date& d)
{
d.Print(); // d1.Print(&d); -> const Date*
}
void TestDate6()
{
Date d1(2022, 5, 18);
d1.Print(); // d1.Print(&d1); -> Date*
Func(d1);
}
int main()
{
TestDate1();
TestDate2();
TestDate3();
TestDate4();
TestDate5();
TestDate6();
TestDate6();
return 0;
}
Test run results

const member

In class , Member functions all contain an implicit this The pointer
such as : The member function in the above figure shows that it is written as :
void Print(Date* const this)//this The pointer itself cannot change , however this The content of the pointer pointing to the space can be changed
{
cout << _year << "-" << _month << "-" << _day << endl;
}
But this can go wrong
void Func(const Date& d)
{
d.Print(); // d.Print(&d); -> const Date*
}
d.Print(); -> Print(&d) -> const Date*
Calling Print() when , The argument is const Date*, however Print() The formal parameter of is Date* const, Permission amplification , An error occurred
How to solve ?
c++ It provides us with a way :
void Print() const
The display is written as :
void Print(const Date* const this)
{
cout << _year << "-" << _month << "-" << _day << endl;
}
It is recommended to add... To all member functions that do not modify member variables
constOrdinary objects and
constObjects can call
Please think about the following questions :
constObject can call nonconstMember function ?- Not
constObject can callconstMember function ?constOther non member functions can be called within member functionsconstMember function ?- Not
constOther functions can be called in member functionsconstMember function ?
- × Permission amplification
- √ Authority reduction
- × Permission amplification
- √ Authority reduction
边栏推荐
- IBL预计算的疑问终于解开了
- Tibetan poem PTA
- 20220215 CTF misc buuctf Xiaoming's safe binwalk analysis DD command separate rar file archpr brute force password cracking
- Redis - cache penetration, cache breakdown, cache avalanche
- 解决 error MSB8031: Building an MFC project for a non-Unicode character set is deprecated.
- Pytorch auto derivation
- Redis - sentinel mode
- Date类的实现
- The quantity and quality of the devil's cold rice 101; Employee management; College entrance examination voluntary filling; Game architecture design
- CSDN常用复杂公式模板记录
猜你喜欢

2022-2028 global PTFE lined valve industry research and trend analysis report

P4 learning - Basic tunneling

Wechat official account development (1) introduction to wechat official account

2022-2028 global carbon fiber room scraper system industry research and trend analysis report

Redis - cache penetration, cache breakdown, cache avalanche

20220215 CTF misc buuctf Xiaoming's safe binwalk analysis DD command separate rar file archpr brute force password cracking

Bugku CTF daily one question dark cloud invitation code

MySQL variables, stored procedures and functions

2022-2028 global retro glass industry research and trend analysis report

CTF tool (1) -- archpr -- including installation / use process
随机推荐
Docsify building a personal minimalist knowledge warehouse
20220215 CTF misc buuctf Xiaoming's safe binwalk analysis DD command separate rar file archpr brute force password cracking
Kubernetes ---- pod configuration container start command
[DaVinci developer topic] -37- detail IRV: introduction to inter runnable variable + configuration
From January 11, 2007 to January 11, 2022, I have been in SAP Chengdu Research Institute for 15 years
运动与健康
给按钮的边框和文字设置不同的背景色
2022-2028 global PTFE lined valve industry research and trend analysis report
Error 2059 when Navicat connects to MySQL
Luogu p1144 shortest circuit count
Get screen height
Get to know the drawing component of flutter - custompaint
20220215 CTF misc buuctf the world in the mirror the use of stegsolve tool data extract
Introduction to ES6 promise, new features of ES7 and es8 async and await
CTF tool (1) -- archpr -- including installation / use process
Basic data structure of redis
Confirm() method of window
Ditto set global paste only text shortcuts
深度学习的历史
Redis based distributed lock