C++極客班第一次作業第一題
題目說明
1)使用正規編碼風格,所有代碼寫在.h和.cpp文件中,不要寫在word或txt等文件中。
2)請在2015年9月19日 00:00前提交作業。
為Date類實現如下成員:
構造器,可以初始化年、月、日。
大于、小于、等于(> 、< 、==)操作符重載,進行日期比較。
print()打印出類似2015-10-1這樣的格式。
然后創建兩個全局函數:
第1個函數 CreatePoints生成10個隨機的Date,并以數組形式返回;
第2個函數 Sort 對第1個函數CreatePoints生成的結果,將其按照從小到大進行排序。
最后在main函數中調用CreatePoints,并調用print將結果打印出來。然后調用Sort函數對前面結果處理后,并再次調用print將結果打印出來。
頭文件
#ifndef _DATE_
#define _DATE_
class Date
{
public:
Date(int y = 0,int m = 0,int d = 0)
:year(y)
,month(m)
,day(d)
{
}
int getyear() const {return year;}
int getmonth() const {return month;}
int getday() const {return day;}
void print();
private:
int year;
int month;
int day;
};
此處需要注意的是操作符重載中一般傳遞const的引用。
inline bool
operator > (const Date& ths,const Date& r)
{
if (ths.getyear() > r.getyear())
{
return true;
}
else if (ths.getyear() < r.getyear())
{
return false;
}
else if (ths.getmonth() > r.getmonth())
{
return true;
}
else if (ths.getmonth() < r.getmonth())
{
return false;
}
else if (ths.getday() > r.getday())
{
return true;
}
else if (ths.getday() < r.getday())
{
return false;
}
else
{
return false;
}
}
inline bool
operator < (const Date& ths, const Date& r)
{
return !(operator > (ths, r));
}
inline bool
operator == (const Date& ths, const Date& r)
{
return (ths.getyear() == r.getyear())&&(ths.getmonth() == r.getmonth())&&(ths.getday() == r.getday());
}
#endif
源文件
#include "GeekbandDate.h"
#include
#include
using namespace std;
void Date::print()
{
printf("%4d-%02d-%02d\n",getyear(),getmonth(),getday());
}
我的代碼中寫了三個set函數,究其原因是對c++類構造函數的理解不夠透徹,以為對私有成員變量的設定必須用成員函數去實現。感覺更好的方式(多數情況)是用成員函數去設定(修改)私有成員變量的值,但在此處似乎沒有必要。
Date* CreatePoints(int n)
{
Date *pdata = new Date[n];
srand(time(0));
for (int i = 0; i < n; i++)
{
pdata[i] = Date(rand()%2015 + 1, rand()%12 + 1, rand()%31 + 1);
}
return pdata;
}
數據的生成采用動態數組的方式,自己當時寫的是棧對象,傳遞指針的方式,以前寫c代碼的時候總是這樣寫,為自己的low表示羞愧!!!
void Sort(Date *date, int n)
{
for (int i = 0; i < n; i++)
{
for (int j = i+1; j < n; j++)
{
if (date[i] > date[j])
{
Date temp ;
temp = date[i];
date[i] = date[j];
date[j] = temp;
}
}
}
}
此處我在當時寫了一段很”詭異“的代碼,老師講完以后還沒有理解,當時在想我為什么會那樣寫。還原了一下寫代碼時的思想活動,是我當時在想類對象成員變量的賦值時把類對象的賦值理解成為類成員變量的依次賦值,編譯器內部就是這么干的,但是我當時是這么想的,感覺自己的想法很奇怪,再次表示羞愧!!!
int main(int argc, char* argv[])
{
const int n = 10;
puts("***********************Before Sort************************");
Date *pdate = CreatePoints(10);
for (int i = 0; i < n; i++)
{
pdate[i].print();
}
Sort(pdate,n);
puts("***********************After Sort************************");
for (i = 0; i < n; i++)
{
pdate[i].print();
}
delete[] pdate;
return 0;
}
總結:自己對構造函數的理解不夠深刻,之所以出現上邊的情況,感覺自己還是在用c語言的思想去寫c++的代碼!