当前位置:网站首页>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
边栏推荐
- Wechat official account development (1) introduction to wechat official account
- The quantity and quality of the devil's cold rice 101; Employee management; College entrance examination voluntary filling; Game architecture design
- P4 learning - p4runtime
- Longest valid bracket
- 20220215 CTF misc buuctf Xiaoming's safe binwalk analysis DD command separate rar file archpr brute force password cracking
- 2022-2028 global herbal diet tea industry research and trend analysis report
- Ditto set global paste only text shortcuts
- Teach you how to use Hal library to get started -- become a lighting master
- left join左连接匹配数据为NULL时显示指定值
- NATs cluster deployment
猜你喜欢

A letter to 5000 fans!

PyTorch安装并使用gpu加速

Oracle-表的创建与管理

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

Ditto set global paste only text shortcuts

P4学习——Basic Tunneling

BeanUtils. Copyproperties() vs. mapstruct

第53章 从业务逻辑实现角度整体性理解程序

Basic knowledge of Embedded Network - introduction of mqtt

CMU15445 (Fall 2019) 之 Project#1 - Buffer Pool 详解
随机推荐
剑指 Offer 19. 正则表达式匹配
Some views on libco
leetcode 474. Ones and zeroes (medium)
优质的水泵 SolidWorks模型素材推荐,不容错过
20220216 misc buuctf backdoor killing (d shield scanning) - clues in the packet (Base64 to image)
C#生成putty格式的ppk文件(支持passphrase)
Ranger plug-in development (Part 2)
Date类的实现
On the application of cluster analysis in work
What SQL statements are supported for data filtering
Rust book materials - yazhijia Library
NATs cluster deployment
Multi graph explanation of resource preemption in yarn capacity scheduling
HDU 2488 A Knight's Journey(DFS)
MySQL storage engine
【2023联发科提前批笔试题】~ 题目及参考答案
Simple application example of rhai script engine
C WinForm program interface optimization example
2022-2028 global weight loss ginger tea industry research and trend analysis report
20220215-ctf-misc-buuctf-einstein-binwalk analyze picture-dd command separate zip file -- look for password in picture attribute