c++运算符重载及日期类的基本实现

 赋值运算符重载基本特点

参数类型:const T&,传递引用可以提高传参效率

返回值类型:T&,返回引用可以提高返回的效率,有返回值目的是为了支持连续赋值

检测是否自己给自己赋值

返回*this :要复合连续赋值的含义

 

赋值运算符只能重载成类的成员函数不能重载成全局函数

原因:赋值运算符如果不显式实现,编译器会生成一个默认的。此时用户再在类外自己实现

一个全局的赋值运算符重载,就和编译器在类中生成的默认赋值运算符重载冲突了,故赋值

运算符重载只能是类的成员函数。

用户没有显式实现时,编译器会生成一个默认赋值运算符重载,以值的方式逐字节拷贝。注

意:内置类型成员变量是直接赋值的,而自定义类型成员变量需要调用对应类的赋值运算符

重载完成赋值

完整代码实现

声明文件

#pragma once
#include <iostream>
using namespace std;
class date
{
public:
	//构造函数会频繁调用,所以放在类里面作为内联函数,减少开销
	date(int year = 1917, int month = 1, int day = 1)
	{
		_year = year;
		_month = month;
		_day = day;
	}
	int GetMonthDay(int year, int month)
	{
		static int days[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };
		int day = days[month];
		if (month == 2 && ((year % 4 == 0 && year % 4 != 0) || (year % 400 == 0)))
		{
			day += 1;
		}
		return day;
	}

	date& operator = (const date& d)//由于不修改加const,由于传参需要拷贝构造所以这里用引用
	{
		if (this != &d)//这里是判断是否在给自己赋值
		{//将this指针的内容赋值给d
			_year = d._year;
			_month = d._month;
			_day = d._day;
		}
		return *this;//用引用返回是为了满足连续运算
	}
	bool operator == (const date& d);
	bool operator >= (const date& d);
	bool operator <= (const date& d);
	bool operator != (const date& d);
	bool operator > (const date& d);
	bool operator < (const date& d);
	date& operator + (int day);
	date& operator += (int day);
	//如果直接按照原来的特性进行重载,则无法区分前置++还是后置++
	//所以这里再后置++增加了一个int参数和前置++构成重载进行区分
	date& operator++();
	date& operator++(int);


private:
	int _year;
	int _month;
	int _day;
};

函数实现文件

#define _CRT_SECURE_NO_WARNINGS
#include "date.h"
bool date::operator==(const date& d)
{
	return _year == d._year
		&& _month == d._month
		&& _day == d._day;
}

bool date::operator > (const date& d)
{
	if ((_year > d._year)
		|| (_year == d._year && _month > d._month)
		|| (_year == d._year && _month == d._month && _day > d._day))
	{
		return true;
	}
	else
		return false;
}
bool date::operator!=(const date& d)
{
	return !(*this == d);
}
bool date::operator<=(const date& d)
{
	return !(*this >d);
}
bool date::operator>=(const date& d)
{
	return (*this == d) ||(*this >d) ;
}
bool date::operator<(const date& d)
{
	return !(*this >= d);
}

date& date::operator += (int day)
{
	_day += day;
	while (_day > GetMonthDay(_year, _month))
	{
		_day -= GetMonthDay(_year, _month);
		++_month;
		if (_month == 13)
		{
			_year++;
			_month = 1;
		}
	}
	return *this;

}

date& date::operator + (int day)
{
	date ret = *this;
	ret += day;
	return ret;
}
date& date::operator++()
{
	*this += 1;
	return *this;
}
date& date::operator++(int)
{
	date tmp(*this);
	*this += 1;
	return tmp;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值