类中构造函数的重载 + 校验



//---------main.cpp------------
#include <iostream>
#include <iomanip>
#include <string>

using namespace std;

class Date
{
private:
	int year,month,day;
	//void init();
public:
	Date(int y=2000,int m=1,int d=1);//设置构造函数的默认参数
	Date(const string &s);//重载构造函数
	bool isLeapYear();
	void print();
private:
	void init();
};
void Date::init()
{
	if(year>5000 || year<1 || month<1 || month>12 || day<1 || day>31) exit(1);  //校验函数  停机
}
Date::Date(int y,int m,int d)
{
	year = y;
	month = m;
	day=d;
	init();
}
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();
}
bool Date::isLeapYear()
{
	return(((year%4 == 0)&&(year%100 != 0))||(year%400 == 0));
}
void Date::print()
{
	std::cout<<"the year is :  "<<year<<"/"<<month<<"/"<<day<<endl;
}
int main(int argc,char **argv)
{
	Date c("2004-12-28");   //构造函数中如果没有const,这里就报错,不知道为什么??
	Date d(2012,12,30);    
	Date e(2014,12);      //默认两个参数
	Date f(2010);         //默认一个参数
	Date g;               //

	c.print();
	d.print();
	e.print();
	f.print();
	g.print();
}

the year is :  2004/12/28
the year is :  2012/12/30
the year is :  2014/12/1
the year is :  2010/1/1
the year is :  2000/1/1
请按任意键继续. . .


void Date::init()为校验函数;


1


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值