运算符重载

/*用友元函数重载常用运算符*/
#include<iostream>
#include<fstream>
using namespace std;
class Person
{
	int a,b,c;
public:
	Person(int i=0,int j=0,int k=0)
	{
		a=i;
		b=j;
		c=k;
	}
	friend istream & operator>>(istream & input,Person & p);
	friend ostream & operator<<(ostream & output,Person & p);
	//friend  Person & operator+=(Person & a1,Person & a2);//重载+=
	friend  Person & operator++(Person & a1);//前置
	friend Person & operator++(Person & a1,int);//后置
	friend Person & operator-(Person & a1);//重载-运算符

};
 istream &operator >>(istream & input,Person & p)//重载输入运算符
{
	input>>p.a>>p.b>>p.c;
	return input;
}
ostream & operator <<(ostream & output,Person & p)//重载输出运算符
{
	output<<p.a<<p.b<<p.c;
	return output;
}

/*Person & operator+=(Person &a1,Person &a2)//重载单目运算符+=
{
	a1.a=a1.a+a2.a;
	a1.b=a1.b+a2.b;
	a1.c=a1.c+a2.c;
	return a1;
}*/

/*Person & operator++(Person & a1)//前置
{
	a1.a++;
	a1.b++;
	a1.c++;
	return a1;
}
Person & operator++(Person & a1,int )//后置
{
	Person a2(a1);
	a2.a++;
	a2.b++;
	a2.c++;
	return a2;
}*/

     Person & operator-(Person & a1)//重载-运算符
	{
		a1.a=-a1.a;
		a1.b=-a1.b;
		a1.c=-a1.c;
		return a1;
	}
int main()
{
	Person a(1,2,3),b;
	cin>>b;
	 b=-b;
	cout<<b<<endl;
	system("pause");
	return 0;
}


#include<iostream>
using namespace std;//输入输出运算符只能用友元函数重载
class Person
{
	int a,b,c;
public:
	Person(int i=0,int j=0,int k=0)
	{
		a=i;
		b=j;
		c=k;
	}
	friend istream & operator>>(istream & input,Person & p);
	friend ostream & operator<<(ostream & output,Person & p);
/*Person & operator+(Person & a1)//成员函数重载+
	{
		Person temp;
		temp.a=a+a1.a;
		temp.b=b+a1.b;
		temp.c=c+a1.c;
		return temp;
	}
*/  
	/* Person & operator +=(Person & a1)
	 {
		 a=a+a1.a;
		 b=b+a1.b;
		 c=c+a1.c;
		 return (*this);
	 }*/
	Person & operator++()
	{
		a++;
		b++;
		c++;
		return(*this);
	}
	Person & operator++(int)//+后置
	{
		Person temp(*this);
		a++;
		b++;
		c++;
		return temp;
	}
};
istream &operator >>(istream & input,Person & p)//重载输入运算符
{
	input>>p.a>>p.b>>p.c;
	return input;
}
ostream & operator <<(ostream & output,Person & p)//重载输出运算符
{
	output<<p.a<<p.b<<p.c;
	return output;
}
int main()
{
   Person a(1,2,3),b,c;
   cin>>b;
   c=++b;
   cout<<c<<endl;
   c=b++;
   cout<<c<<endl;
   system("pause");
   return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

不会敲代码的小帅

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

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

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

打赏作者

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

抵扣说明:

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

余额充值