重载运算符的两种方式

第一种就是把运算符重载函数作为类内成员函数,他可以通过this 指针自由的访问本类的数据成员,因此可以少些一个参数

Complex operator +(Complex &);
以下是把运算符重载函数作为类内成员函数 重载‘+’的源代码

#include <iostream>
using namespace std;
class Complex
{
	public:
		Complex(int ,int );
		void set_C(int ,int );
		void show_C();
		Complex operator +(Complex &);
		void set_C(int );//重载函数
	private:
		int real;
		int imag;
};
Complex::Complex(int a=10,int b=10)
{
	real=a;
	imag=b;
}
void Complex::set_C(int a)
{
	real=a;
}
void Complex::set_C(int a,int b)
{
	real=a;
	imag=b;
}
void Complex::show_C()
{
	cout<<real<<'+'<<imag<<'i'<<endl;
}
Complex Complex::operator +(Complex&a2)
{
	Complex a1;
	a1.real=real+a2.real;
	a1.imag=imag+a2.imag;
	return a1;
}
int main()
{
	Complex C1,C2,C3;
	C1.set_C(2,5);
	C1.set_C(-2);
	C3=C2+C1;
	C1.show_C();
	C2.show_C();
	C3.show_C();
	 return 0;
} 
第二种就是用普通函数重载(注意需要在类内声明为友元函数)

双目运算符重载为友元函数时,由于友元函数不是该类的成员函数,因此在函数的形参列表里必须有两个参数,不能省略

friend Complex operator +(Complex &a1,Complex &a2);//声明为友元函数 
以下是用普通函数重载“+”的源代码

#include <iostream>
using namespace std;
class Complex 
{
	public:
		Complex(int ,int );
		void set_C(int ,int );
		void show_C();
		friend Complex operator +(Complex &a1,Complex &a2);//声明为友元函数 
		void set_C(int );
	private:
		int real;
		int imag;
};
Complex::Complex(int a=10,int b=10)
{
	real=a;
	imag=b;
}
void Complex::set_C(int a)
{
	real=a;
}
void Complex::set_C(int a,int b)
{
	real=a;
	imag=b;
}
void Complex::show_C()
{
	cout<<real<<'+'<<imag<<'i'<<endl;
}
Complex operator +(Complex &a1,Complex&a2)
{
	Complex a;
	a.real=a1.real+a2.real;
	a.imag=a1.imag+a2.imag;
	return a;
}
int main()
{
	Complex C1,C2,C3;
	C1.set_C(2,5);
	C1.set_C(-2);
	C3=C2+C1;
	C1.show_C();
	C2.show_C();
	C3.show_C();
	 return 0;
} 
1、C++规定,赋值运算符“=”、下标运算符“[ ]”、函数调用运算符"( )"、成员运算符“->”必须作为成员函数重载。

2、流插入“<<”和流提取运算符“>>”、类型转换运算符不能定义为类的成员函数,只能作为友元函数。
3、一般将单目运算符和复合运算符(+=、-=、/=、*=、&=、!=、^=、%=、>>=、<<=)重载为成员函数。

4、一般将双目运算符重载为友元函数。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值