C 實現日期類

2021-08-17 12:53:24 字數 2750 閱讀 4384

date(日期)類:

練習實現類的成員函式。

運算子的過載

date.h

#include class  date

date(int year, int month, int day); //全預設建構函式

date(const date& d); //拷貝構造

date& operator=(const date& d); //賦值運算子的過載 >> 返回引用,防止連續賦值

~date(){}

bool isinvalid(); //判斷日期是否合法

bool isleapyear(int year); //檢測閏年

int getmonthday(int year, int month);//得到這個月有多少天

void show();

bool operator==(const date& d); //運算子過載

bool operator!=(const date& d);

bool operator>=(const date& d);

bool operator<=(const date& d);

bool operator>(const date& d);

bool operator<(const date& d);

//日期計算器

date operator+(int day);

date& operator+=(int day);

date operator-(int day);

date& operator-=(int day);

int operator-(const date& d);

date& operator++()//前置---比後置效率高(不建立物件)

date operator++(int)//後置(建立空間, 呼叫了拷貝構造)

date& operator--()//前置

date operator--(int)//後置 int佔位

private: //成員變數

int _year;

int _month;

int _day;

};

date.cpp

#include "test_class.h"

#include /類成員函式

date::date(int year = 1900, int month = 1, int day = 1) //全預設建構函式

}date::date(const date& d)

bool date::isinvalid()

bool date::isleapyear(int year) //檢測閏年

int date::getmonthday(int year, int month)//得到這個月有多少天

; int day = days[month];

if (month == 2 && isleapyear(year))

return day;

}void date::show()

/運算子過載

date& date::operator=(const date& d) //賦值運算子的過載 >> 返回引用,防止連續賦值

return *this;

}bool date::operator==(const date& d)

bool date::operator!=(const date& d)

bool date::operator>=(const date& d)

bool date::operator<=(const date& d)

bool date::operator>(const date& d)

bool date::operator<(const date& d)

//日期計算

date date::operator+(int day)

date ret(*this);

ret._day += day;

while (ret.isinvalid() == false)//加的day不合法

//while (ret._day > getmonthday(ret._year, ret._month)) //加完後只要天不合法即為不合法 }

return ret;

}date& date::operator+=(int day)

//d1 - 100

date date::operator-(int day)

date ret(*this);

ret._day -= day;

while (ret._day <= 0) //小於等於0都不合法

else

//得到上個月的天

int monthday = getmonthday(ret._year, ret._month);

//當前的天數+得到的上個月的天數

ret._day += monthday;

} return ret;

}date& date::operator-=(int day)

//d1 - d2

int date::operator-(const date& d)

while (min < max)

return retday*flag;

}

C 實現日期類

功能 實現日期的簡單操作 基本的成員函式 建構函式,拷貝建構函式,析構函式,賦值運算子過載,操作符過載 兩個日期間比較大小 日期類功能函式 1 計算乙個日期加上多少天數後的日期 2 把該日期改為加上指定數目的天數後的日期 3 乙個日期減上多少天數後的日期 4 把該日期改為減去指定數目的天數後的日期 ...

C 實現日期類

預設成員函式的應用場景 date date1 當我們例項化乙個物件date1時,就會呼叫 建構函式,所以我們可以使用建構函式對物件進行初始化。date date2 date1 當我們例項化物件date2的同時將乙個已存在的物件的內容拷貝過來,就會呼叫拷貝建構函式。date date3 date3 d...

借助c 實現日期類

本篇部落格借用c 簡單實現乙個日期類 其中包括日期計算器,日期比較大小。接下來我將注釋寫到 中方便理解。date.h pragma once class date 拷貝建構函式 date const date d return this 析構函式 date 列印日期 void show 判斷是否為閏...