当前位置:网站首页>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
const
Ordinary objects and
const
Objects can call
Please think about the following questions :
const
Object can call nonconst
Member function ?- Not
const
Object can callconst
Member function ?const
Other non member functions can be called within member functionsconst
Member function ?- Not
const
Other functions can be called in member functionsconst
Member function ?
- × Permission amplification
- √ Authority reduction
- × Permission amplification
- √ Authority reduction
边栏推荐
- C language file operation for conquering C language
- IBL预计算的疑问终于解开了
- Teach you how to use Hal library to get started -- become a lighting master
- [DaVinci developer topic] -37- detail IRV: introduction to inter runnable variable + configuration
- BeanUtils. Copyproperties() vs. mapstruct
- leetcode 474. Ones and zeroes (medium)
- P4 learning - Basic tunneling
- 2022-2028 global retro glass industry research and trend analysis report
- New trend of embedded software development: Devops
- 获取屏幕高度
猜你喜欢
Oracle临时表详解
【日常记录】——对BigDecimal除法运算时遇到的Bug
P4 learning - Basic tunneling
Docsify building a personal minimalist knowledge warehouse
2022-2028 global carbon fiber room scraper system industry research and trend analysis report
The quantity and quality of the devil's cold rice 101; Employee management; College entrance examination voluntary filling; Game architecture design
2022-2028 global ultra high purity electrolytic iron sheet industry research and trend analysis report
初识 Flutter 的绘图组件 — CustomPaint
2022-2028 global herbal diet tea industry research and trend analysis report
2022-2028 global weight loss ginger tea industry research and trend analysis report
随机推荐
Integer to hexadecimal string PTA
Experiment 8 T-SQL, stored procedure
"Experience" my understanding of user growth "new users"
Introduction to ES6 promise, new features of ES7 and es8 async and await
Authentication principle of Ranger plug-in
双链表:初始化 插入 删除 遍历
C#生成putty格式的ppk文件(支持passphrase)
第53章 从业务逻辑实现角度整体性理解程序
Mindjet mindmanager2022 mind map decompression installer tutorial
2022-2028 global capsule shell industry research and trend analysis report
Using Excel to quickly generate SQL statements
Ranger plug-in development (Part 2)
20220215 CTF misc buuctf Xiaoming's safe binwalk analysis DD command separate rar file archpr brute force password cracking
C WinForm program interface optimization example
C#生成putty格式的ppk文件(支持passphrase)
Problem solving: how to manage thread_local pointer variables
Solving the weird problem that the query conditions affect the value of query fields in MySQL query
leetcode 474. Ones and Zeroes 一和零(中等)
Error 2059 when Navicat connects to MySQL
Interface documentation system - Yapi