爲Date類實現以下成員:ios
而後建立兩個全局函數:c++
最後在main函數中調用CreatePoints,並調用print將結果打印出來。而後調用Sort函數對前面結果處理後,並再次調用print將結果打印出來。數組
//定義Date頭文件 #ifndef DATE_H_INCLUDED #define DATE_H_INCLUDED #include <iostream> using namespace std; class Date; void Sort(Date* date, const int& n); void CreatePoints(Date* date, const int& n); class Date { public: Date(int Year=0,int Month=0,int Day=0) :year(Year), month(Month) ,day(Day){} bool operator > (const Date& d2) { if(year>d2.year||(year==d2.year&&month>d2.month||(year==year&&month==d2.month&&day>d2.day))) { return true; } else { return false; } } bool operator < (const Date d2) { if(year<d2.year||(year==d2.year&&month<d2.month)||(year==d2.year&&month==d2.month&&day<d2.day)) { return true; } else { return false; } } bool operator ==(const Date& d2) { if(year==d2.year&&month==d2.month&&day==d2.day) return true; return false; } bool isleagl(Date& date) { if((date.getmonth()==4||date.getmonth()==6||date.getmonth()==9||date.getmonth()==11)&&date.getday()>30) { return false; } else if(date.getmonth()==2) { if((date.getyear()%4==0&&date.getyear()%100!=0)||date.getyear()%400==0) { if(date.getday()>29) { return false; } } else if(date.getday()>28) { return false; } } return true; } int getyear() const {return year;} int getmonth()const {return month;} int getday() const {return day;} void print() { cout<<year<<"-"<<month<<"-"<<day<<endl; } friend void CreatePoints(Date* date,const int& n); friend void Sort(Date* date, const int& n); private: int year; int month; int day; }; #endif // DATE_H_INCLUDED
#include<stdlib.h> using namespace std; //日期合法性檢查 bool isleagl(Date& date) { if((date.getmonth()==4||date.getmonth()==6||date.getmonth()==9||date.getmonth()==11)&&date.getday()>30) { return false; } else if(date.getmonth()==2) { if((date.getyear()%4==0&&date.getyear()%100!=0)||date.getyear()%400==0) { if(date.getday()>29) { return false; } } else if(date.getday()>28) { return false; } } return true; } //建立日期並初始化 void CreatePoints(Date *date,const int&n) { for(int i=0;i<n;) { int Year=rand()%3000+1; int Month=rand()%12+1; int Day=rand()%31+1; date[i]=Date(Year,Month,Day); if(isleagl(date[i])) { ++i; } } } //日期排序 void Sort(Date* date, const int& n) { Date temp; for (int i=0; i<n; ++i) { for (int j=0; j<n-i-1; ++j) { if (date[j] > date[j+1]) { temp = date[j]; date[j] = date[j+1]; date[j+1] = temp; } } } } int main() { Date *date=new Date[10]; CreatePoints(date,10); cout<<"CreatData:"<<endl; for (int i = 0; i < 10; i++ ) { date[i].print(); } Sort(date,10); cout << "after sort:" << endl; for (int i = 0; i < 10; i++ ) { date[i].print(); } delete[] date; return 0; }
運行結果:函數