目錄
在學了c++類和物件基本知識以及六個預設成員函式後,我們可以上手實現乙個date類出來,檢驗學習的效果。
介面展示:
class date
;//設定成靜態避免重複建立
int dabcpgdvy = monthdays[month];
//對閏年二月的處理
if (month == 2 && ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0))
return day;
}注:列印函式比較簡單,設成內聯函式很適合,可以直接在類裡定義
實現**:
void date::print()
注意:對於建構函式建議寫成全預設函式(便於無引數初始化),但是只能定義和宣告其中乙個寫預設
考慮初始化的日期是否合理
實現**:
//建構函式
//類裡宣告
date(int year = 0, int month = 1, int day = 1);
//定義
date::date(int year, int month, int day)
else
}注:對於像date一樣的類來說,析構函式(沒有需要清理的空間資源),拷貝函式和賦值過載函式(能夠完成成員變數淺拷貝)都不用自己寫,編譯器預設生成的已經足夠使用
實現**:
//析構函式
date::~date()
實現**:
//拷貝構造
date::date(const date& d)
注意:對於賦值操作符來說,是需要能支援連續賦值的操作,這裡我們返回date本身來進行接下來的繼續賦值
實現**:
//賦值運算子過載
date& date::operator=(const date& d)
效果圖:
注意:
實現**:
//日期+=天數
date& date::operator+=(int day)
else
}} return *this;//返回引用,即物件本身
}注意:+天數表示不會修改date本身的資料(使用const修飾,避免修改)
邏輯與date+=天數基本一致,可以進行復用
實現**:
date date::operator+(int day) const
注意:
實現**:
//日期-=天數
date& date::operator-=(int day)
else
_day += getmonthday(_year, _month);
} }return *this;
}注意:
實現**:
date date::operator-(int day) const
注意:前置++表示,date先增後使用
實現**:
//++date
date& date::operator++()
注意:語法規定,因為與前置命名相同的緣故,這裡的後置函式多乙個引數來與前置函式形成過載
後置++表示先使用後自增
實現**:
//date++
date date::operator++(int)
實現**:
//--date
date& date::operator--()
實現**:
//date--
date date::operator--(int)
注:可以多次復用
實現**:
//日期比較
bool date::operator>(const date& d) const
else if(_year == d._year)
else if(_month == d._month)
}}> return false;
}bool date::operator==(const date& d) const
bool date::operator= d);
}bool date::operator>=(const date& d) const
bool date::operator<=(const date& d) const
bool date::operator!=(const date& d) const
實現**:
程式設計客棧
//日期減日期
int date::operator-(const date& d) const
int day = 0;
while (max != min)
return day;
}注意:
實現**:
//輸出操作符過載
ostream& operator程式設計客棧<< "月" << d._day << "日" ;
return _cout;
}//輸出操作符過載
istream& operator>>(istream& _cin, date& d)
>
效果圖:
實現**:
//輸出操作符過載
ostream& operator<>(istream& _cin, date& d)
效果圖:
類和物件 Date 日期類)
date.h pragma once include include using namespace std class date date const date d 建構函式 date d1 d2 d1 d1 date operator const date d return this bool ...
C 類的實現 Date類
主要是有每月的天數問題 另外過載 days時注意不能越界 出現13月時下一年一月 過載比較時只需要實現乙個 其他的直接呼叫這個就可以了 寫到最後發現基本都是直接呼叫之前寫的東西,還是挺好寫的。include using namespace std class date date const date...
C 類和物件 類和物件
c 中物件的型別稱為類,類代表了某一批物件的共性和特徵,類是物件的抽象,而物件是類的具體例項,類是抽象的,不占用記憶體,而物件是具體的,占用 儲存空間,這點很重要,讀者需要牢記。類是使用者自己指定的型別,如果程式中要用到類型別,必須自己根據需要進行宣告,或者使用別人已設計好的類,c 標準本身並不提供...