c++程序:定义一个日期类Date,包括年、月、日三个数据成员,以及一个求第二天日期的成员函数

如题所述

#include <iostream>
using namespace std;
class Date//默认一个月是30天
{
public:
Date(int x=2011,int y=1,int z=8):year(x),month(y),day(z)
{
cout<<"初始化日期是:"<<year<<"年"<<month<<"月"<<day<<"日"<<endl;
}
~Date(){}
void NextDate()
{
day++;
if (day>30)
{
day=day-30;
month++;
}
if (month>12)
{
month=month-12;
year++;
}
cout<<"the next date is "<<year<<" 年"<<month<<" 月"<<day<<" 日"<<endl;
}

private:
int year;
int month;
int day;

};
int main()
{
Date date1;
Date date2(2011,12,30);
date1.NextDate();
date2.NextDate();
return 0;
}
使用的编译环境是vc6.0,你可以试试的 往后的知识内容你可以试试操作符号的重载,也很方便的
温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2018-08-29
#include <iostream.h>
class Date
{
private:
int year,month,day;
public:
Date(int y, int m, int d)
{
year=y;
month=m;
day=d;
}
void nextday();
void display()
{
cout<<year<<"/"<<month<<"/"<<day<<endl;
}
};
void Date::nextday()
{
int totaldays[2][12]={{31,28,31,30,31,30,31,31,30,31,30,31},{31,29,31,30,31,30,31,31,30,31,30,31}};day++;int leap=(year%400==0||year%4==0&&year%100!=0);
if(day>totaldays[leap][month-1])
{
day=1;
month++;
if(month>12)
{
month=1;
year++;
}
}
}
void main()
{
int d,m,y;
cout<<"请输入年、月、日:\n";
cin>>y>>m>>d;
Date d1(y,m,d);
cout<<"今天是:";
d1.display();
d1.nextday();
cout<<"明天是:";
d1.display();
}本回答被网友采纳
第2个回答  2011-01-08
正在复习模拟电路,复习的蛋疼,逛逛百度知道,嘿!看到个感兴趣的问题,甩开模电写写代码...写的不是很健壮.........

class Date{
private:
int year;
int month;
int day;
public:
String nextDayDate(){
this.day++;
if(month==2){
if (this.year % 400 == 0 || (this.year % 4 == 0 &&this. year % 100 != 0)) {
// 闰年二月有29天,平年28天
if(this.day>29){
this.day = 1;
this.month++;
if(this.month>12)
this.year++;
}
} else {
if(this.day>28){
this.day = 1;
this.month++;
if(this.month>12)
this.year++;
}
}else if (month == 4 || month == 6 || month == 9 || month == 11){//4,6,9,11月,有30天
if(this.day>30)
this.month++;
if(this.month>12)
this.year++;

}
else{//1,3,5,7,8,10,12月,有31天
if(this.day>31)
this.month++;
if(this.month>12)
this.year++;

}
return this.year+"年"+month+"月"+day+"日";
}
}
第3个回答  2011-01-08
使用mfc 中的CDateTime,或COleDateTime。各种求法都有,还有源码。非常智能。
相似回答