当前位置:网站首页>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
边栏推荐
- Sword finger offer 19 Regular Expression Matching
- 2022-2028 global capsule shell industry research and trend analysis report
- File reading and writing for rust file system processing - rust Practice Guide
- 实验八 T-sql,存储过程
- 解决 error MSB8031: Building an MFC project for a non-Unicode character set is deprecated.
- Rhai - rust's embedded scripting engine
- Redis - sentinel mode
- 20220215 CTF misc buuctf the world in the mirror the use of stegsolve tool data extract
- New trend of embedded software development: Devops
- Introduction to ES6 promise, new features of ES7 and es8 async and await
猜你喜欢

Date类的实现

2022-2028 global 3D printing ASA consumables industry research and trend analysis report

Confirm() method of window

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

Two-stage RO: part 1

C # generates PPK files in putty format (supports passphrase)

20220216 misc buuctf another world WinHex, ASCII conversion flag zip file extraction and repair if you give me three days of brightness zip to rar, Morse code waveform conversion mysterious tornado br

2022-2028 global ethylene oxide scrubber industry research and trend analysis report

Mindjet mindmanager2022 mind map decompression installer tutorial

Deployment of mini version message queue based on redis6.0
随机推荐
解决 error MSB8031: Building an MFC project for a non-Unicode character set is deprecated.
2022-2028 global herbal diet tea industry research and trend analysis report
2022-2028 global public address fire alarm system industry research and trend analysis report
"Experience" my understanding of user growth "new users"
leetcode 474. Ones and Zeroes 一和零(中等)
Basic data structure of redis
2022-2028 global ICT test probe industry research and trend analysis report
2022-2028 global capsule shell industry research and trend analysis report
2022-2028 global ultra high purity electrolytic iron sheet industry research and trend analysis report
Ybtoj exchange game [tree chain splitting, line segment tree merging]
Mindjet mindmanager2022 mind map decompression installer tutorial
The programmer's girlfriend gave me a fatigue driving test
SAP ui5 beginner tutorial 19 - SAP ui5 data types and complex data binding
C WinForm program interface optimization example
20220216 misc buuctf backdoor killing (d shield scanning) - clues in the packet (Base64 to image)
2022就要过去一半了,挣钱好难
深度学习的历史
Tibetan poem PTA
2022-2028 global electric yacht industry research and trend analysis report
CentOS installation starts redis