C++——运算符重载

运算符重载是具有特护函数名的函数,它的引入是为了增强代码的可读性

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

注意:

  • 不能通过连接其他符号来创建新的操作符,比如:operator@
  • 重载操作符参数不能全为内置类型,必须有一个类类型或者枚举类型的操作数 
  • 用于内置类型的操作数,其含义不能改变
  • 作为类成员的重载函数时,其形参看起来比操作数数目少1个成员函数(操作符有一个默认的形参this指针,限定为第一个形参)

有如下代码:

class Date
{
public:
	Date(int year = 1900, 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;
}
void test()
{
	Date d1(2020, 10, 12);
	Date d2(2020, 10, 21);
	cout << (d1 == d2) << endl;
}
int main()
{
	test();
	return 0;
}

 运行结果为:

由于函数operator==在类外定义,无法访问类内的私有成员变量,类的封装性无法保证

当我们把operator==函数作为类的成员函数时,会显示参数太多,则说明有一个隐藏的形参this指针

正确代码如下:

class Date
{
public:
	Date(int year = 1900, int month = 1, int day = 1)
	{
		_year = year;
		_month = month;
		_day = day;
	}
	bool operator==(const Date& d2)
	{
		return _year == d2._year
			&& _month == d2._month
			&& _day == d2._day;
	}
private:
	int _year;
	int _month;
	int _day;
};
  • .*、::、sizeof、?:、.  以上五个运算符不能重载
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值