运算符重载

一、运算符重载

当运算符被用于类类型的对象时,C++语⾔允许我们通过运算符重载的形式指定新的含义。C++规定类类型对象用使运算符时,必须转换成调⽤对应运算符重载,若没有对应的运算符重载,则会编译报错。

运算符重载是具有特殊名字的函数,他的名字是由operator和后面要定义的运算符共同构成。和其他函数⼀样,它也具有其返回类型和参数列表以及函数体。

重载运算符函数的参数个数和该运算符作用的运算对象数量一样多。一元运算符有一个参数,二元运算符有两个参数,二元运算符的左侧运算对象传给第一个参数,右侧运算对象传给第二个参数。

如果一个重载运算符函数是成员函数,则它的第一个运算对象默认传给隐式的this指针,因此运算符重载作为成员函数时,参数⽐运算对象少一个。

运算符重载以后,其优先级和结合性与对应的内置类型运算符保持一致。

不能通过连接语法中没有的符号来创建新的操作符:⽐如operator@。

.  *  ::  sizeof  ?:  . 注意以上5个运算符不能重载。(选择题里面常考,⼤家要记一下)

重载操作符至少有一个类类型参数,不能通过运算符重载改变内置类型对象的含义,如: int operator+(int x, int y)

一个类需要重载哪些运算符,是看哪些运算符重载后有意义,⽐如Date类重载operator-就有意义,但是重载operator+就没有意义。

二、赋值运算符重载

赋值运算符重载是一个默认成员函数,用于完成两个已经存在的对象直接的拷贝赋值,这里要注意跟拷贝构造区分,拷贝构造用于一个对象拷贝初始化给另一个要创建的对象。

赋值运算符重载的特点:

1. 赋值运算符重载是一个运算符重载,规定必须重载为成员函数。赋值运算重载的参数建议写成 const 当前类类型引用,否则会传值传参会有拷贝。

2. 有返回值,且建议写成当前类类型引用,引用返回可以提高效率,有返回值目的是为了⽀持连续赋值场景。

3. 没有显式实现时,编译器会自动生成一个默认赋值运算符重载,默认赋值运算符重载行为跟默认构造函数类似,对内置类型成员变量会完成值拷贝/浅拷贝(一个字节、一个字节的拷贝),对自定义类型 成员变量会调用他的拷贝构造。

4. 像Date这样的类成员变量全是内置类型且没有指向什么资源,编译器自动生成的赋值运算符重载就可以完成需要的拷贝,所以不需要我们显示实现赋值运算符重载。像Stack这样的类,虽然也都是内置类型,但是_a指向了资源,编译器自动生成的赋值运算符重载完成的值拷贝/浅拷贝不符合我们的需求,所以需要我们自己实现深拷贝(对指向的资源也进行拷贝)。像MyQueue这样的类型内部主要是自定义类型Stack成员,编译器自动生成的赋值运算符重载会调用Stack的赋值运算符重载, 也不需要我们显示实现MyQueue的赋值运算符重载。这里还有⼀个⼩技巧,如果一个类显示实现了析构并释放资源,那么他就需要显示写赋值运算符重载,否则就不需要。

下面我将插入一段代码,作为运算符重载和赋值运算符重载的应用:

#include<iostream>
using namespace std;

class Date
{
public:
	void Print()
	{
		std::cout << _year << "/" << _month << "/" << _day << std::endl;
	}
	// 获取某年某月的天数
	int GetMonthDay(int year, int month)
	{
		if (month <= 0)
		{
			month = 12;
		}
		else if (month >= 13)
		{
			month = 1;
		}
		switch (month)
		{
		case 1:
			return 31;
		case 2:
			if ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0))
			{
				return 29;
			}
			else
			{
				return 28;
			}
		case 3:
			return 30;
		case 4:
			return 30;
		case 5:
			return 31;
		case 6:
			return 30;
		case 7:
			return 31;
		case 8:
			return 31;
		case 9:
			return 30;
		case 10:
			return 31;
		case 11:
			return 30;
		case 12:
			return 31;
		}
		return -1;
	}
	// 全缺省的构造函数
	Date(int year = 1900, int month = 1, int day = 1)
		:
		_year(year),
		_month(month),
		_day(day)
	{

	}
	// 拷贝构造函数
	// d2(d1)
	Date(const Date& d)
	{
		_year = d._year;
		_month = d._month;
		_day = d._day;
	}
	// 赋值运算符重载
	// d2 = d3 -> d2.operator=(&d2, d3)
	Date& operator=(const Date& d)
	{
		this->_day = d._day;
		this->_month = d._month;
		this->_year = d._year;
		return *this;
	}
	// 析构函数
	~Date()
	{
		_year = 0;
		_month = 0;
		_day = 0;
	}
	// 日期+=天数
	Date& operator+=(int day)
	{
		this->_day += day;
		while (_day > GetMonthDay(_year, _month))
		{
			if (_month <= 12 && _month > 0)
			{
				_day -= GetMonthDay(_year, _month);
				_month++;
			}
			else if (_month < 1)
			{
				_year--;
				_month = 12;
			}
			else
			{
				_month = 1;
				_year++;
			}
		}

		return *this;
	}
	// 日期+天数
	Date operator+(int day)
	{
		Date tmp = *this;
		tmp += day;
		return tmp;
	}
	// 日期-天数
	Date operator-(int day)
	{
		Date tmp = *this;
		tmp -= day;
		return tmp;
	}
	// 日期-=天数
	Date& operator-=(int day)
	{
		this->_day -= day;
		while (_day < 1)
		{
			if (_month <= 12 && _month > 0)
			{
				_day += GetMonthDay(_year, _month-1);
				_month--;
			}
			else if (_month < 1)
			{
				_year--;
				_month = 12;
			}
			else
			{
				_month = 1;
				_year++;
			}
		}

		return *this;
	}
	// 前置++
	Date& operator++()
	{
		*this += 1;
		return *this;
	}
	// 后置++
	Date operator++(int)
	{
		*this += 1;
		return *this;
	}
	// 后置--
	Date operator--(int)
	{
		*this -= 1;
		return *this;
	}
	// 前置--
	Date& operator--()
	{
		*this -= 1;
		return *this;
	}
	// >运算符重载
	bool operator>(const Date& d)
	{
		if (_year > d._year)
		{
			return true;
		}
		else if (_year == d._year)
		{
			if (_month > d._month)
			{
				return true;
			}
			else if (_month == d._month)
			{
				if (_day > d._day)
				{
					return true;
				}
				else
				{
					return false;
				}
			}
			else
			{
				return false;
			}
		}
		else
		{
			return false;
		}
	}
	// ==运算符重载
	bool operator==(const Date& d)
	{
		if (_year > d._year)
		{
			return false;
		}
		else if (_year == d._year)
		{
			if (_month > d._month)
			{
				return false;
			}
			else if (_month == d._month)
			{
				if (_day == d._day)
				{
					return true;
				}
				else
				{
					return false;
				}
			}
			else
			{
				return false;
			}
		}
		else
		{
			return false;
		}
	}
	// >=运算符重载
	bool operator >= (const Date& d)
	{
		if (*this > d || *this == d)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	// <运算符重载
	bool operator < (const Date& d)
	{
		if (*this >= d)
		{
			return false;
		}
		else
		{
			return true;
		}
	}
	// <=运算符重载
	bool operator <= (const Date& d)
	{
		if (*this > d)
		{
			return false;
		}
		else
		{
			return true;
		}
	}
	// !=运算符重载
	bool operator != (const Date& d)
	{
		if (*this == d)
		{
			return false;
		}
		else
		{
			return true;
		}
	}
	// 日期-日期 返回天数
	int operator-(const Date& d)
	{
		
		int sum = 0;
		if (*this > d)
		{
			Date left = *this;
			Date right = d;

			//对日进行处理
			sum += left._day - 1;
			left._day = 1;

			sum -= right._day - 1;
			right._day = 1;

			//对月进行处理
			while (left._month > 1)
			{
				sum += GetMonthDay(left._year, left._month - 1);
				left._month--;
			}

			while (right._month > 1)
			{
				sum -= GetMonthDay(right._year, right._month - 1);
				right._month--;
			}

			//对年进行处理
			while (left._year > right._year)
			{
				if ((left._year % 400 == 0) || (left._year % 4 == 0 && left._year % 100 != 0))
				{
					sum += 366;
					left._year--;
				}
				else
				{
					sum += 365;
					left._year--;
				}
			}

			return sum;
		}
		else if (*this == d)
		{
			return 0;
		}
		else
		{
			Date left = d;
			Date right = *this;

			//对日进行处理
			sum += left._day - 1;
			left._day = 1;

			sum -= right._day - 1;
			right._day = 1;

			//对月进行处理
			while (left._month > 1)
			{
				sum += GetMonthDay(left._year, left._month - 1);
				left._month--;
			}

			while (right._month > 1)
			{
				sum -= GetMonthDay(right._year, right._month - 1);
				right._month--;
			}

			//对年进行处理
			while (left._year > right._year)
			{
				if ((left._year % 400 == 0) || (left._year % 4 == 0 && left._year % 100 != 0))
				{
					sum += 366;
					left._year--;
				}
				else
				{
					sum += 365;
					left._year--;
				}
			}

			return -sum;
		}
	}
private:
	int _year;
	int _month;
	int _day;
};

int main()
{
	Date p1 = { 2024,8,18 };
	Date p2 = { 2024,9,1 };

	int result = p2 - p1;
	cout << result << endl;

	return 0;
}

三、取地址运算符重载

1.const成员函数

将const修饰的成员函数称之为const成员函数,const修饰成员函数放到成员函数参数列表的后面。

const实际修饰该成员函数隐含的this指针,表明在该成员函数中不能对类的任何成员进⾏修改。const 修饰Date类的Print成员函数,Print隐含的this指针由 Date* const this 变为 const Date* const this

#include<iostream>
using namespace std;
class Date
{
public:
    Date(int year = 1, int month = 1, int day = 1)
    {
        _year = year;
        _month = month;
        _day = day;
    }

    // void Print(const Date* const this) const
    void Print() const
    {
        cout << _year << "-" << _month << "-" << _day << endl;
    }

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


int main()
{
    // 这⾥⾮const对象也可以调⽤const成员函数是⼀种权限的缩⼩
    Date d1(2024, 7, 5);
    d1.Print();
    const Date d2(2024, 8, 5);
    d2.Print();
    return 0;
}

2. 取地址运算符重载

取地址运算符重载分为普通取地址运算符重载和const取地址运算符重载,一般这两个函数编译器自动生成的就可以够我们用了,不需要去显示实现。除非一些很特殊的场景,⽐如我们不想让别⼈取到当前类对象的地址,就可以自己实现一份,胡乱返回一个地址。

class Date
{
public :
    Date* operator&()
    {
        return this;
        // return nullptr;
    }

    const Date* operator&()const
    {
        return this;
        // return nullptr;
    }

private :
    int _year ; // 年
    int _month ; // ⽉
    int _day ; // ⽇
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值