天天看點

【2016.4.1】CDate類相關注記

編寫一個日期類CDate,使得能夠設定日期、顯示日期、實作前置自增後置自增的重載函數。

該類的架構定義如下:

class CDate  
{  
private:  
    int year, month, day;      //年月日     
    static const int days[12]; //定義月份的天數,預設是閏年,用法:day=days[month-1]  
public:  
    CDate(int Y = 2016, int M = 1, int D = 1);//帶有預設值的構造函數  
    ~CDate() {}                    //析構函數  
    bool set(int Y = 2016, int M = 1, int D = 1);  //帶有預設值的設定日期函數,如果日期異常,則傳回false  
    static bool is_leap_year(int Year){return ((Year % 4 == 0 && Year % 100 != 0) || (Year % 400 == 0));}  //傳回是否是閏年  
    CDate& operator++();   // ++a //前置後置自重載函數實作  
    CDate operator++(int); //a++  
    friend ostream& operator<<(ostream& out, const CDate& variable);//定義提取運算符重載  
}; 
           

其中有幾點需要注意:

1.類中常量實作辦法

static const int days[12];	//定義月份的天數,預設是閏年,用法:day=days[month-1]
           

這一個數組是用來儲存常量值的,也就是12個月份的天數。要将 其定義為static靜态類型的常數組,需要注意 此時不能被初始化,因為類隻是一個聲明,沒有開辟空間。其 初始化要在實作檔案中或類外定義方法的檔案中實作, 不加static但是要加域名:

const int CDate::days[12] = { 31,28,31,30,31,30,31,31,30,31,30,31 };
           

注意此時不要帶static。

關于類中定義常量還有以下兩個常用方法:

a.)使用枚舉類型。如在類中定義:

class CDate
{
public:
enum days={january=31,february=28}//....etc
} 
           

b.)使用指針。在類中定義常量指針,在類外定義常數組,然後在構造函數中将數組位址指派給指針:

const int Days[12]={31,28,31,30,31,30,31,31,30,31,30,31 }; 
class CDate  
{      
public:   
CDate(int Y = 2016, int M = 1, int D = 1):days(Days);   
private:   
const int* const days;   
};  
           

類中關于靜态變量的定義也是類似:需要在 類外定義且不加static但是要加域名:

class CDate  
{      
private:   
static int how_much;   
};
int CDate::how_much=12;  
           

類中關于靜态函數同樣如此:需要在 類外定義且不加static但是要加域名:

class CDate
{
public:
static bool is_leap_year(int Year);//傳回是否是閏年
};
bool CDate::is_leap_year(int Year)
{
return ((Year % 4 == 0 && Year % 100 != 0) || (Year % 400 == 0));
}
           

2.前置後置自增運算符重載函數

CDate& operator++();	// ++a			//前置後置自重載函數實作
CDate operator++(int);	//a++
           

第二個函數中的int是形式上區分标志,無實際意義但是不可缺少。

注意到兩個函數的傳回值類型不同。第一個前置自增運算符傳回的是引用,也就是*this,它将自身自增以後傳回它自身。後者傳回的是一個臨時變量,它先儲存原來*this的值,然後*this自增,之後傳回這個臨時變量,也就是原來的*this。其實作如下:

CDate& CDate::operator++()// ++a
{
int add_year = 0, add_month = 0;
if (day == days[month - 1])
  add_month = 1, day = 1;
else
  day += 1;
///if month==12, add_month==1 or 0, 13%12==1,12%12==0
month = (add_year = month + add_month)==12? 12:add_year%12;  
year += add_year / 12;//or month==11, add_month==1,12%12==0
return *this;//else month = (month + add_month)% 12
}
CDate CDate::operator++(int)//a++
{
CDate temp = *this;
++*this;
return temp;
}
           

其抽象以後如下:

CDate& CDate::operator++()// ++a
{
//對*this進行操作
//.....<span style="white-space:pre">			</span>
return *this;//傳回*this<span style="white-space:pre">					</span>
}
CDate CDate::operator++(int) //a++
{
CDate temp=*this;//儲存原來的*this到臨時變量
++*this;//*this自增
return temp;//傳回原來的*this
}
           
上一篇: Es6-Number

繼續閱讀