美文网首页干货
C++ geekband home work review 1

C++ geekband home work review 1

作者: Wanggl | 来源:发表于2015-10-03 11:52 被阅读218次

C++极客班第一次作业第一题

题目说明

1)使用正规编码风格,所有代码写在.h和.cpp文件中,不要写在wordtxt等文件中。

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++的代码!

相关文章

网友评论

    本文标题:C++ geekband home work review 1

    本文链接:https://www.haomeiwen.com/subject/lksgcttx.html