回 帖 发 新 帖 刷新版面

主题:高手与菜鸟的对话 请教高手帮改写一个c++

请教高手帮改写一个c++的题目。刚刚学c++,自己编了很久很久都编不出。先谢了!

1.改写下面程序,要求在程序中的日期类的基础上,实现一个可进行加天数操作获得另一个日期,以及进行日期减日期操作获得相隔天数的日期类,并进行应用程序设计:    创建2005.8.21和2008.8.8两个日期,并计算中间相隔的天数,前者加上300天会是什么日子。 

[code=c]
#include<iostream>
#include<iomanip>
using namespace std;

class Date{
  int year, month, day;
  void init();
public:
  Date(const string& s);
  Date(int y=2000, int m=1, int d=1);
  bool isLeapYear()const;
  friend ostream& operator<<(ostream& o, const Date& d);
};
void Date::init(){
  if(year>5000 || year<1 || month<1 || month>12 || day<1 || day>31)
    exit(1);  // 停机
}
Date::Date(const string& s){
  year = atoi(s.substr(0,4).c_str());
  month = atoi(s.substr(5,2).c_str());
  day = atoi(s.substr(8,2).c_str());
  init();
}
Date::Date(int y, int m, int d){
  year=y, month=m, day=d;
  init();
}
bool Date::isLeapYear()const{
  return (year % 4==0 && year % 100 )|| year % 400==0;
}
ostream& operator<<(ostream& o, const Date& d){
  o<<setfill('0')<<setw(4)<<d.year<<'-'<<setw(2)<<d.month<<'-';
  return o<<setw(2)<<d.day<<'\n'<<setfill(' ');
}
int main(){
  Date c("2005-12-28");
  Date d(2003,12,6);
  Date e(2002);
  Date f(2002,12);
  Date g;
  cout<<c<<d<<e<<f<<g;
}
[/code]

回复列表 (共1个回复)

沙发

重载运算符+和-,你再试试。

我来回复

您尚未登录,请登录后再回复。点此登录或注册