C++运算符重载详解(日期类实操)

前言:为什么要实现运算符重载?

在C语言中,对于内置类型,我们可以根据符号>、<、==等去直接比较大小,但是对于自定义来说,肯定不能直接比较大小,例如下面的日期类,想要比较两个两个日期的大小,或者相差多少天,直接写运算符肯定是不行的。

class Date
{
private:
	int _year;
	int _month;
	int _day;
};

这时候就需要运算符重载出马了!

运算符重载的概念:

运算符重载是具有特殊函数名的函数,也具有其返回值类型,函数名字以及参数列表,其返回值类

型与参数列表与普通的函数类似。

函数名字为:

关键字operator后面接需要重载的运算符符号

函数原型:

返回值类型 operator操作符(参数列表)。

注意:

  • 不能通过连接其他符号来创建新的操作符:比如operator@ 
  • 重载操作符必须有一个类类型参数
  • 用于内置类型的运算符,其含义不能改变,例如:内置的整型+,不 能改变其含义
  • 作为类成员函数重载时,其形参看起来比操作数数目少1,因为成员函数的第一个参数为隐藏的this
  • .* :: sizeof ?: . 注意以上5个运算符不能重载。这个经常在笔试选择题中出现。
  • 此时括号的意义就是控制优先级

日期类运算符实操

头文件(函数的声明)

class Date
{
public:
	// 获取某年某月的天数
	int GetMonthDay(int year, int month);
	//打印日期
	void Print();

	// 全缺省的构造函数
	Date(int year = 1900, int month = 1, int day = 1);
	// 拷贝构造函数
  // d2(d1)
	Date(const Date& d);
	// 赋值运算符重载
  // d2 = d3 -> d2.operator=(&d2, d3)
	Date& operator=(const Date& d);
	// 析构函数
	~Date();
	// 日期+=天数
	Date& operator+=(int day);
	// 日期+天数
	Date operator+(int day);
	// 日期-天数
	Date operator-(int day);
	// 日期-=天数
	Date& operator-=(int day);
	// 前置++
	Date& operator++();
	// 后置++
	Date operator++(int);
	// 后置--
	Date operator--(int);
	// 前置--
	Date& operator--();

	// >运算符重载
	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);
	// 日期-日期 返回天数
	int operator-(const Date& d);
private:
	int _year;
	int _month;
	int _day;
};

重载实现(函数的定义):

int Date::GetMonthDay(int year, int month)
{
	int arr[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };
	//判断闰年
	if ((month == 2) && ((year % 4 == 0 && year % 100 == 0) || (year % 400 == 0)))
		return 29;
	return arr[month];
}

void Date::Print()
{
	cout << _year << '-' << _month << '-' << _day;
}


//构造函数的参数声明给,定义不给
Date::Date(int year, int month, int day)
{
	_year = year;
	_month = month;
	_day = day;
}


Date::Date(const Date& d)
{
	_year = d._year;
	_month = d._month;
	_day = d._day;
}

Date& Date::operator=(const Date& d)
{
	_year = d._year;
	_month = d._month;
	_day = d._day;
	return *this;
}

Date::~Date()
{
	_year = 0;
	_month = 0;
	_day = 0;
}

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)
		return true;
	if (_year == d._year && _month < d._month)
		return true;
	if (_year == d._year && _month == d._month && _day < d._day)
		return true;
	return false;
}

bool Date::operator>(const Date& d)
{
	return !operator<(d) && !operator==(d);
}

bool Date::operator>=(const Date& d)
{
	return operator==(d) || operator>(d);
}

bool Date::operator <= (const Date& d)
{
	return !operator>(d);
}

bool Date::operator != (const Date& d)
{
	return !operator==(d);
}


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

//前置++和后置++的区别就是构成重载,参数加上int
//在调用的时候,有参数会调用前置++,没有参数会调用后置++
Date& Date::operator++()
{
	(*this) += 1;
	return *this;
}

 // 注意:后置++是先使用后+1,因此需要返回+1之前的旧值,故需在实现时需要先将this保存一份,然后给this+1
 //       而temp是临时对象,因此只能以值的方式返回,不能返回引用


Date Date::operator++(int)
{
	//调用拷贝构造函数
	Date tmp(*this);
	(*this) += 1;
	return tmp;
}

Date& Date::operator-=(int day)
{
	_day -= day;
	while (_day <= 0)
	{
		_month--;
		if (_month == 0)
		{
			_year--;
			_month = 12;
		}
		_day += GetMonthDay(_year, _month);
	}
	return *this;
}


int Date::operator-(const Date& d)
{
	int cnt = 0;
	while (*this != d)
	{
		cnt++;
		(*this)--;
	}
	return cnt;
}

Date& Date::operator--()
{
	(*this) -= 1;
	return *this;
}

Date Date::operator--(int)
{
	Date tmp(*this);
	(*this) -= 1;
	return tmp;
}

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

重载过程中的注意点:

  • 构造函数如果声明和定义分离,声明需要将参数赋缺省值,定义不需要写,以防混淆。
  • 传参数时尽量都要用引用传参,可以提高传参的效率
  • 传返回值时,如果返回值在调用完这个函数没有被销毁,需要引用返回,如果销毁了,直接返回。
  • 复用已经实现的函数

关于返回值到底是引用还是不需要引用?

看返回值如果是*this,就用引用返回(出了函数作用域,不会销毁);

返回值如果是在函数体内创建的临时变量,就不用引用返回(出了作用域,临时变量会销毁)。

赋值运算符重载:

1. 赋值运算符重载格式

  • 参数类型:const T&,传递引用可以提高传参效率
  • 返回值类型:T&,返回引用可以提高返回的效率,有返回值目的是为了支持连续赋值检测是否自己给自己赋值
  • 返回*this :要复合连续赋值的含义

operator= 我们不写,编译器会生成默认的operator=,跟拷贝构造的行为类似,内置类型值拷贝,自定义类型调用他的赋值。

Date MyQueue也可以不写,默认生成operator= 就可以使用。Stack必须自己实现operator=,实现深拷贝。

2、前置++后置++的重载区别


 // 前置++和后置++都是一元运算符,为了让前置++与后置++形成能正确重载
 // C++规定:后置++重载时多增加一个int类型的参数,但调用函数时该参数不用传递,编译器自动传递
 // 注意:后置++是先使用后+1,因此需要返回+1之前的旧值,故需在实现时需要先将this保存一份,然后给this+1(调用拷贝构造函数
 //       而temp是临时对象,因此只能以值的方式返回,不能返回引用

this指向的对象函数结束后不会销毁,故以引用方式返回提高效率

输入流输出流操作符重载

为什么cin cout能够自动识别任意类型的数据呢?

本质上就是函数的重载

原码:

ostream& operator<<(ostream& out, const Date& d)
{
	out << d._year << "年" << d._month << "月" << d._day << "日" << endl;

	return out;
}

istream& operator>>(istream& in, const Date& d)
{
	in >> d._year >> d._month >> d._day;

	return in;
}

总结:

其他的运算符一般是实现成成员函数,<< >>运算符必须是实现到全局,这样才能让流对象做第一个参数,才符合可读性。不然可读性很差,像下面定义在类的内部:

重载流操作符为什么必须用引用?

如果我们使用值传送来传递一个流给函数,那么在函数里要生成一个该流的临时变量,生成临时变量的时候,就要调用对应的拷贝构造函数,并且这个拷贝构造函数必须是以一个值传送的流作为参数的——但是流就是没有这样的拷贝构造函数

分析:

流本质是为了解决,自定义类型的输入和输出问题,printf scanf 无法解决自定义类型的输入输出问题

面向对象 + 运算符重载解决!

成员函数定义的规则:

  1. 能定义成const的成员函数都应该定义成const,这样const对象(权限平移)和非const对象(权限缩小)都可以调用
  2. 要修改成员变量的成员函数,不能定义成const

注意本质修饰的是成员函数,全局函数都没有this指针,如何修饰呢?

注意+=两种实现方式的不同所带来的影响

  • 56
    点赞
  • 52
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 55
    评论
评论 55
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

可涵不会debug

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

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

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

打赏作者

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

抵扣说明:

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

余额充值