C++赋值运算符重载

运算符重载

C++为了增强代码的可读性引入了运算符重载,运算符重载是具有特殊函数名的函数,它同样具有返回值、函数名及参数列表。

复制代码
class Date
{
public:
	Date(int year = 1, int month = 1, int day = 1)
	{
		_year = year;
		_month = month;
		_day = day;
	}
	bool operator<(Date& d)//运算符重载
	{
		if (_year < d._year)
		{
			return true;
		}
		else if (_year == d._year && _month < d._month)
		{
			return true;
		}
		else if (_year == d._year && _month == d._month && _day < d._day)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	bool DateLess(Date& d)
	{
		if (_year < d._year)
		{
			return true;
		}
		else if (_year == d._year && _month < d._month)
		{
			return true;
		}
		else if (_year == d._year && _month == d._month && _day < d._day)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
private:
	int _year;
	int _month;
	int _day;
};
int main()
{
	Date d1(2025, 8, 1);
	Date d2(2024, 8, 1);
	cout << d1.DateLess(d2) << endl;//调用函数
	cout << (d1 < d2) << endl;//调用函数重载
	return 0;
}

通过上述代码可以看出,运算符重载相比函数调用更易懂,增强了代码的可读性。

函数原型:返回值类型 operator操作符(参数列表)

**注:**不能通过链接C++外的符合创造出新的操作符

重载操作符必须有一个类类型对象,形参比操作数少一个是因为成员函数存在隐藏的this指针

用于内置类型的运算符其含义不能发生改变

'.*' '::' 'sizeof' '?:' '.'这五个运算符不能重载

赋值运算符重载

复制代码
class Date
{
public:
	Date(int year = 1, int month = 1, int day = 1)
	{
		_year = year;
		_month = month;
		_day = day;
	}
	bool operator!=(Date& d)
	{
		return _year != d._year || _month != d._month || _day != d._day;
	}
	Date& operator=(Date& d)//赋值运算符重载
	{
		if (*this != d)//避免自己给自己赋值
		{
			_year = d._year;
			_month = d._month;
			_day = d._day;
		}
		return *this;//返回*this,这样符合连续赋值的含义
	}
	void Print()
	{
		cout << _year << "年" << _month << "月" << _day << "日" << endl;
	}
private:
	int _year;
	int _month;
	int _day;
};
int main()
{
	Date d(2021, 2, 5);
	Date d1;
	d1 = d;
	d.Print();
	d1.Print();
	return 0;
}

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

赋值运算符与拷贝构造函数相似,如果涉及到资源申请必须显示定义。

前置++与后置++重载

复制代码
	Date& operator++()//前置++
	{
		_day += 1;
		return *this;
	}
	Date& operator++(int)//后置++
	{
		Date tmp(*this);
		_day += 1;
		return tmp;
	}

由于前置++和后置++都是一元运算符,因此为了让其能够形成正确的重载,C++规定后置++重载时要加一个int类型的参数,但在调用该函数时参数不需要进行传递,编译器会自动传递。

相关推荐
hqwest7 小时前
码上通QT实战08--导航按钮切换界面
开发语言·qt·slot·信号与槽·connect·signals·emit
CSARImage7 小时前
C++读取exe程序标准输出
c++
一只小bit7 小时前
Qt 常用控件详解:按钮类 / 显示类 / 输入类属性、信号与实战示例
前端·c++·qt·gui
AC赳赳老秦7 小时前
DeepSeek 私有化部署避坑指南:敏感数据本地化处理与合规性检测详解
大数据·开发语言·数据库·人工智能·自动化·php·deepseek
一条大祥脚7 小时前
26.1.9 轮廓线dp 状压最短路 构造
数据结构·c++·算法
不知道累,只知道类8 小时前
深入理解 Java 虚拟线程 (Project Loom)
java·开发语言
国强_dev8 小时前
Python 的“非直接原因”报错
开发语言·python
YMatrix 官方技术社区8 小时前
YMatrix 存储引擎解密:MARS3 存储引擎如何超越传统行存、列存实现“时序+分析“场景性能大幅提升?
开发语言·数据库·时序数据库·数据库架构·智慧工厂·存储引擎·ymatrix
项目題供诗8 小时前
C语言基础(一)
c++
玖疯子8 小时前
技术文章大纲:Bug悬案侦破大会
开发语言·ar