类中构造函数的重载


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

using namespace std;

class Date
{
private:
	int year,month,day;
public:
	Date(int y=2000,int m=1,int d=1);//设置构造函数的默认参数
	Date(const string &s);//重载构造函数
	bool isLeapYear();
	void print();
};

Date::Date(int y,int m,int d)
{
	year = y;
	month = m;
	day=d;
}
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());
}
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;               //无参数对象定义,不要加括号。如果加括号,就变成了,返回Date型的函数调用或声明了。有意思吧!!!

	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
请按任意键继续. . .




1


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值