C++极简总结 — 运算符重载 (一)

运算符重载

运算符重载规则

  1. 符合语法规则
  2. 不能创建新的运算符
  3. 不能重载 . ,.* ,?:
  4. 重载要保证原有基本语义不变。
    运算符重载实际上就是函数的重载。

运算符重载形式

1.成员函数重载运算符
<返回值类型> operator<运算符>(参数)
参数个数与运算符的操作数个数有关。且注意,每个非静态成员函数带有自引用参数 this 指针。 所以成员函数重载运算符需要的参数的个数总比它的操作数少一个。

class Point
{
public:
	Point(int x = 0, int y = 0)
	{
		_x = x;
		_y = y;
	}
	~Point()
	{
		;// cout<<"destructor"<<endl;
	}
	Point operator+(Point pt);
	void printPoint()
	{
		cout<<"["<<_x<<","<<_y<<"]"<<endl;
	}
private:
	int _x;
	int _y;
};
Point Point::operator+(Point pt)
{
	Point temp;
	temp._x = this->_x + pt._x;
	temp._y = this->_y + pt._y;
	return temp;
}

int main()
{
	Point p1(1,2);
	Point p2(1,4);
	p1 = p1 + p2;
	p1.printPoint(); 
	return 0;
}		

2.友元函数重载运算符
friend <返回值类型> operator<运算符>(参数) 友元函数不是类的成员,没有this指针,所以参数必须显示声名。友元函数运算符重载需要的参数个数与操作数一样多。

class Point
{
public:
	Point(int x = 0, int y = 0)
	{
		_x = x;
		_y = y;
	}
	~Point()
	{
		;// cout<<"destructor"<<endl;
	}
	friend Point operator+(Point pt1,Point pt2);
	void printPoint()
	{
		cout<<"["<<_x<<","<<_y<<"]"<<endl;
	}
private:
	int _x;
	int _y;
};
Point operator+(Point pt1,Point pt2)
{
	Point temp;
	temp._x = pt1._x + pt2._x;
	temp._y = pt2._y + pt2._y;
	return temp;
}

int main()
{
	Point p1(1,2);
	Point p2(1,4);
	p1 = p1 + p2;
	p1.printPoint(); 
	return 0;
}		

友元函数重载运算符有一定限制

  • 赋值运算符不能用友元函数重载,-=,+=运算符也不可以。
  • 友元函数不能重载(),[],->
  • 重载++ 和 -- 运算符是友元函数需要引用参数。(如下面的单目运算符重载)

单目运算符重载

举例: ++和- - 的重载

1. 用成员函数重载

前缀++:
<返回类型>::operator++();
后缀++
<返回类型>::operator++(int);
int 参数表明调用该函数时运算符"++"应该放在操作数的后面,且参数本身没有被用到。

class Point
{
public:
	Point(int x = 0, int y = 0)
	{
		_x = x;
		_y = y;
	}
	~Point()
	{
		;// cout<<"destructor"<<endl;
	}              
	friend Point operator+(Point pt1,Point pt2int);
	Point operator++();    //前缀              
	Point operator++(int); //后缀
	void printPoint()
	{
		cout<<"["<<_x<<","<<_y<<"]"<<endl;
	}
private:
	int _x;
	int _y;
};
Point operator+(Point pt1,Point pt2)
{
	Point temp;
	temp._x = pt1._x + pt2._x;
	temp._y = pt2._y + pt2._y;
	return temp;
}

Point Point::operator++()
{
	_x++;
	_y++;
	return *this;
}
Point Point::operator++(int)
{
	Point temp;
	temp._x = _x++;
	temp._y = _y++;
	return temp;
}


int main()
{
	Point p1(1,2);
	Point p2(1,4);
	Point p3;
	p1 = p1 + p2;
	p1.printPoint();
	p3 = ++p1;
	p1.printPoint();
	p3.printPoint();
    p3 = p2++;
    p2.printPoint();
	p3.printPoint();
	return 0;
}		
1. 用友元函数重载

由于友元函数没有this指针,要修改操作数的值,就需要使用引用传参。
前缀++:
<返回类型>::operator++(<类名>&);
后缀++
<返回类型>::operator++(<类名>&,int);

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

FlyDremever

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值