C++ 写一个Data类的注意问题

 

目录

 

Data类

声明和定义分离的一些问题

日期判断

拷贝构造

运算符重载

赋值运算符重载

用operator+ 实现两个日期类相加

复用 ”+"实现 “+=”

operator-=


Data类

声明和定义分离的一些问题

声明里面我们不带缺省参数,定义我们给缺省参数,如下面两段代码:

Data.h


#pragma once
#include<iostream>
using namespace std;
class Data
{
public:
	Data(int year,int month,int day);

private:
	int _year;
	int _month;
	int _day;

};
Data.cpp



#include"Data.h"

	Data::Data(int year=1 , int month=1 , int day=1 )
	{
		_year = year;
		_month = month;
		_day = day;
	}

现在我们在main函数调用:

d1没报错,d2报错了:

这是因为我们main函数那个文件包的是.h文件,声明我们没有给缺省参数,声明就好比一种承诺,

没给参数,我们d2没有默认参数就过不了。

我们给个默认参数看看:

#pragma once
#include<iostream>
using namespace std;
class Data
{
public:
	Data(int year = 1, int month = 1, int day = 1);
private:
	int _year;
	int _month;
	int _day;

 };

声明和定义不能同时给默认参数,我们把定义的默认参数去了就可以了。

OK,我们写个print函数就可以把日期打印出来看看了:

Data.cpp



void Data:: print()
	{
		cout << _year << "年" << _month << "月" << _day << "日" << endl;
	}

我们发现上面这段日期是有问题的,有点的是闰年,有的是13月,是一些不合法日期,所以我们要加日期有效判断。

日期判断

引用上一篇文章写的:



	int Getmonth(int year,int month)
	{
		int GetArry[13] = {0, 31,28,30,31,30,31,30,31,30,31,30,31 };
		
		if (month==2&&(month % 4 == 0 && month % 10 == 0 || month % 400 != 0))
		{
			return 29;
		}
	return GetArry[month];
	}
	
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

孙鹏宇.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值