运算符重载的非成员函数形式

运算符重载为非成员函数的规则:

  • 函数的形参代表依自左至右次序排列的各操作数
  • 重载为非成员函数时
  • 参数个数 = 原操作数个数(后置++、--除外,它们仍然为了区分前置++、--要强行加个int)
  • 至少应该有一个自定义类型的参数(例如"Typ1 operator + (int, double)"非法)
  • 如果在运算符的重载函数中需要操作某类对象的私有成员,可以将此函数声明为该类的友元


运算符重载为非成员函数的使用方法:

  • 重载双目运算符U:oprd1 U oprd2 = operator U (oprd1, oprd2)
  • 前置单目运算符U:U oprd = operator U(oprd)
  • 后置单目运算符U:oprd U = operator U(oprd, 0)


例子:重载负数的加减法以及"<<"运算符:

  • 将+、-重载为非成员函数,并将其声明为复数类的友元,两个操作数都是复数类的常引用
  • 将<<(双目运算符)重载为非成员函数,并将其声明为复数类的友元,它的左操作数是std::ostream引用,右操作数为复数类的常引用,返回std::ostream引用


#include<iostream>
using namespace std;
class Complex
{
	public:
		Complex(double r = 0.0, double i = 0.0):  r(r),  i(i)  {}  
		friend Complex operator + (const Complex &c1, const Complex &c2);
		friend Complex operator - (const Complex &c1, const Complex &c2);
		friend ostream &operator << (ostream &out, const Complex &c);
	private:    
		double r;
		double i;
};

Complex operator + (const Complex &c1, const Complex &c2)
{
	return Complex(c1.r+c2.r, c1.i+c2.i);
}
Complex operator - (const Complex &c1, const Complex &c2)
{
	return Complex(c1.r-c2.r, c1.i-c2.i);
}
ostream &operator << (ostream &out, const Complex &c)
{
	out<<"("<<c.r<<", "<<c.i<<")";
	return out;
}

int main(void)
{    
	Complex c1(5, 4), c2(2, 10), c3;
	c3 = c1 - c2;
	cout<<"c3 = c1 - c2 = "<<c3<< endl;
	c3 = c1 + c2;
	cout<<"c3 = c1 + c2 = "<<c3<< endl;
	return 0;
}

  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值