3738 - C++作业4-1:定义一个带重载构造函数的日期类(分值较大)

定义一个带重载构造函数的日期类Date,数据成员有年、月、日;成员函数包括:一个带参数的构造函数Date(int,int,int),一个不带参数的构造函数(设置默认值为1900-1-1),一个按“年-月-日”格式显示日期的函数void show(),一个对数据成员赋值的函数void init(int,int,int)。
主函数中对类的测试要求:
1. 分别使用两个不同的重载构造函数创建两个日期类对象(必须为d1,d2,d2初始值为2100-12-12);
2. 按“年-月-日”格式分别显示两个对象的值;
3. 输入数据,用init函数为d1赋值;
2.按“年-月-日”格式显示对象d1的值;。

题目输入

给d1赋值的数据

例如:

2011 4 29

题目输出

d1的默认值

d2的初始值

d1赋值后的值

例如:

1900-1-1

2100-12-12
2011-4-29

输入/输出样例

题目输入

2000 2 29

题目输出

1900-1-1
2100-12-12
2000-2-29

提示

主函数main()中对象的声明、测试:

int y,m,d;

Date d1,d2(2100,12,12);

d1.show();

d2.show();

cin>>y>>m>>d;

d1.init(y,m,d);

d1.show();

C++解答

#include <iostream>
using namespace std;
class Date{
 public:
	Date(int y,int m,int d);
	Date();
	void show();
	void init();
private:
	int year;
	int month;
	int day; 
}; 
Date::Date(int y,int m,int d){
	year=y;
	month=m;
	day=d;
}
Date::Date(){
	int y=1900;
	int m=1;
	int d=1;
	year=y;
	month=m;
	day=d;
}
void Date::show(){
	cout<<year<<"-"<<month<<"-"<<day<<endl;
}
void Date::init(){
	cin>>year>>month>>day;
}
int main(){
	Date d1,d;
	Date d2(2100,12,12);
    d.init();
    d1.show();
    d2.show();
    d.show();
 return 0;
}

提示

主函数main()中对象的声明、测试:

int y,m,d;

Date d1,d2(2100,12,12);

d1.show();

d2.show();

cin>>y>>m>>d;

d1.init(y,m,d);

d1.show();

时间限制 1 秒
内存限制 32 MB
讨论 统计
上一题 下一题