cpp--赋值运算符重载,浅显易懂!

赋值运算符重载

运算符重载

概念

运算符重载允许程序员重新定义运算符(如 +、-、*、/ 等)在自定义数据类型上的行为,使得这些运算符能够像作用于基本数据类型那样,方便地用于操作自定义的数据类型,增强了代码的可读性和可维护性,让代码看起来更加自然和直观

由来

c++为了增强代码的可读性引入了运算符重载,运算符是具有特殊函数名的函数,也具有其返回值类型,函数名字以及参数列表,其返回值类型与参数列表的普通的函数类似

特征

函数名字为:关键字operator后面接需要重载的运算符符号
函数原型:返回值类型operator操作符(参数列表)
注意:

  • 不能通过连接其他符号来创建新的操作符:比如operator@
  • 重载操作符必须有一个类类型参数
  • 用于内置类型的运算符,其含义不能改变,例如:内置类型+,不能改变其含义
  • 作为类成员函数重载时,其形参看起来比操作数数目少1,因为成员函数的第一个参数为隐藏的this
  • | .* | :: | sizeof | ?: | . | 注意以上5个运算符不能重载。这个经常在笔试选择题中出现
#include <iostream>
using namespace std;
class Date
{
   
   
	friend bool operator==(const Date& d1, const Date& d2);
	//如果不定义友元函数则会导致私有日期类成员无法访问的问题
public:
	Date(int year=1, int month=1, int day=1)
	{
   
   
		_year = year;
		_month = month;
		_day = day;
	}
	
private:
	int _year;
	int _month;
	int _day;
};
bool operator==(const Date& d1, const Date& d2)
{
   
   
	return d1._year == d2._year
		&& d1._month == d2._month
		&& d1._day == d2._day;
}
int main()
{
   
   
	Date d1(2025, 1, 23);
	Date d2;//编译器自动调用默认构造函数

	if (d1 == d2)
	{
   
   
		cout << "日期相等" << endl;
	}
	else
	{
   
   
		cout << "日期不相等" << endl;
	}

}

除了这种运算符重载,我们还可以将运算符重载函数作为成员函数,不过写法有些不同

#include <iostream>
using namespace std;
class Date
{
   
   
	friend bool operator==(const Date& d1, const Date& d2);
public:
	//作为类成员函数重载时,其形参看起来比操作数数目少1,因为成员函数的第一个参数为隐藏的this
	//即this->_year = year; this->_month = month ; this->_day = day
	Date(int year=1, int month=1, int day=1)
	{
   
   
		_year = year;
		_month = month;
		_day = day;
	}
	bool operator==(const Date& d)
	{
   
   
		return _year == d._year
			&& _month == d._month
			&& _day == d._day;
	}
private:
	int _year;
	int _month;
	int _day;
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值