C++类和对象(中)——运算符重载&赋值运算符重载

2 阅读2分钟

前言

这篇文章笔者继续讲类的两个重要的默认成员函数——运算符重载和赋值运算符重载

1.运算符重载

自定义类型的对象无法直接比较大小,必须自定义一个函数来比较,这个函数也就是运算符重载 如果自定义类型对象使用预算符时没有对应的预算符重载,那么编译报错

  • 预算符重载时具有特殊名字的函数,operator[运算符]构成,具有返回类型,参数列表和函数体
  • 重载运算符函数的参数个数和运算符作用的运算对象个数一样多
  • 如果把重载运算符函数写作成员函数,那么第一个运算对象默认传给this指针.参数比运算对象少一个
  • .* :: sizeof ?: . 均不能楚重载
  • 重载<<和>>需要重载为全局函数 比如我实现的一部分日期类:
class Date
{
public:
	Date(int year = 1, int month = 1, int day = 1)
	{
		_year = year;
		_month = month;
		_day = day;
	}
	void Print()
	{
		cout << _year << "-" << _month << "-" << _day;
	}
	/*int GetYear()
	{
		return _year;
	}*/
	bool operator==(const Date &d2)
	{
		return _year == d2._year
			&& _month == d2._month
			&& _day == d2._day;
	}
	bool operator<(const Date& d2)
	{
		return _year > d2._year || (_year == d2._year && _month == d2._month) || (_year == d2._year && _month == d2._month && _day > d2._day);
	}
	//d1+100
	Date operator+(int day);
	//d1-100
	Date operator-(int day);
	//d1 - d2
	int operator-(const Date &d2);

private:
	int _year;
	int _month;
	int _day;
};
//bool operator<(Date d1,Date d2)
//{
//
//}
//bool operator==(Date d1, Date d2)
//{
//	return d1._year == d2._year
//		&& d1._month == d2._month
//		&& d1._day == d2._day;
//}
int main()
{
	Date x1(2026, 3, 24);
	Date x2(2026, 3, 26);
	x1.operator==(x2);
	x1 == x2;
	return 0;
}
int main()
{

	return 0;
}

这段代码就是对运算符重载的距离,需要注意的是由于_day这些元素在类中被私有化了,所以最好的解决方法是重载为成员函数,但是由于成员函数第一个参数默认传给this指针,因此的 不用写直接写d2,而且在传参的过程中最好使用引用传参避免过多的拷贝构造。

2.赋值运算符重载

赋值运算符重载用于实现两个已经存在的对象直接拷贝复制(拷贝构造用于一个对象拷贝初始化另一个已经存在的对象)

  • 赋值运算符必须重载为成员函数,而且参数建议写成const当前类类型的引用,减少引用传参的拷贝构造
  • 有返回值时建议返回值写成当前类类型的引用来减少拷贝构造
  • 没有显示实现时系统会默认生成一个赋值运算符重载完成浅拷贝,如果显示实现了析构并且释放资源那么必显示实现赋值运算符重载

结语

下一篇就是类和对象(中)的最后一部分——完成一个Date类