C++运算符的重载

运算符的重载

C++通过运算符重载的操作赋予了运算符新的功能,使得预定义的运算符可以对我们自己定义的数据类型进行操作,扩展了运算符的功能

#include <iostream>
using namespace std;
//定义com类,该类有两个成员real 和 img,重载运算符“+”
class com
{
private:
	int real, img;
public:
	com(int real = 0, int img = 0)
	{
		this->real = real;
		this->img = img;
	}
	//函数参数比原来的操作数少一个是因为:
	//this指针隐式的访问了类的一个对象,它充当了运算符函数最左边的操作数

	com operator + (com x)//当 com类 + com类时,执行(x1,y1) = (x1+x2,y1+y2)
	{
		return com(this->real + x.real, this->img + x.img);
	}

	com operator + (int x)//当 com类 + int数值时,执行(x1,y1) = (x1+x,y1)
	{
		return com(this->real + x, this->img);
	}
	//友元函数没有this指针,因此操作数的个数没有变化
	//所有的操作数都必须通过函数的形参进行传递,函数的参数与操作数自左至右一一对应

	friend com operator + (int x, com y)//当 int数值 +com类时,执行(x1,y1) = (x+x1,y1)
	{
		return com(x + y.real, y.img);
	}
	void show()
	{
		cout << real << "," << img << endl;
	}
};


int main()
{
	com a;
	com b(10, 10);
	com c(100, 100);

	a = b + c;// com类 + com类
	a.show();

	a = b + 1;//  com类 + int数值
	a.show();

	a = 1 + c;//  int数值 + com类
	a.show();


	system("pause");
	return 0;
}

在这里插入图片描述
转载自:黑凤梨の博客

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值