Get the App
SLTechnology News&Howtos  ›  Development  › 

How to implement the date class of C++ class and object

Shulou Source: shulou.com Published: 2022-06-03 16:49:13 09月16日 Update

This article mainly introduces the C++ class and object date class how to achieve, the article is very detailed, has a certain reference value, interested friends must read it!

1. Laying the groundwork before realization

Before implementing, we need to write the class, which contains member functions and member variables.

For the date class, the copy construction and assignment operators don't have to be written, but it doesn't matter if I write it in the class.

# includeusing std::cout;using std::endl;using std::cin;class Date {public:// constructor Date (int year = 0, int month = 1, int day = 1) {if (year > = 0 & & month > 0 & & month0 & & day = inline bool operator > = (const Date& d); / / GetMonthDay (_ year, _ month)) {_ day-= GetMonthDay (_ year, _ month); _ month++; if (_ month > 12) {_ year++ _ month = 1;}} else {* this-= (- day);} return * this;} 2.2 date-= number of days

Here, like the + = operator overload function, it is necessary to determine whether the day is positive or negative.

Date& Date::operator-= (int day) {if (day > 0) {_ day-= day; while (_ day operator overload bool Date::operator > (const Date& d) {if (_ year > d._year) {return true;} else if (_ year = = d._year) {if (_ month > d._month) {return true } else if (_ month = = d._month) {if (_ day > d._day) {return true;} return false;} 2.10 = = operator overload bool Date::operator== (const Date& d) {return _ year = = d._year & & _ month = = d._month & & _ day = = d.daylight;} 2.11 > = operator overload

Here we begin to reuse the operator overload functions of > and = =

Bool Date::operator > = (const Date& d) {return (* this > d) | | (* this = = d);} 2.12d);} 2.13

Tags: Date number of days function operator operation reuse operator negative object clocking content variable member time article discord it doesn't matter value interest parameter Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia Shulou Technology Huawei Linux MariaDB