C++的一些基本知识:运算符重载为友元函数

一般情况下,将运算符重载为类的成员函数,是较好的选择。

但有时,重载为成员函数不能满足使用要求,重载为普通函数,又不能访问类的私有成员,所以需要将运算符重载为友元

如重载为成员函数时,他不能处理5+c的情况

如下,定义一个复数类

创建 复数对象a,对a进行运算

class Complex {
	double real, imag;
public :
	Complex(double r, double imag) :real(r), imag(imag) {};
	Complex operator+(double r);
};
Complex Complex::operator+(double r) {//可以解释a+5
	return Complex(r + real, imag);
}
int main() {
	Complex a(1,2);
	a = a + 5;//等价于a.operator+(5);
	a = 5 + a;//报错
}

根据使用需求,所以我们应该把运算符号重载为普通函数好些

但是普通函数又不能访问私有成员,所以,需要将运算符+重载为友元。

friend Complex operator+(double r, const Complex& s);//友元

普通函数实现:

Complex operator+(double r, const Complex& s) {//普通函数
	return Complex(r + s.real,s.imag);
}

完整代码:

class Complex {
	double real, imag;
public :
	int GetReal() { return real; }
	int Getimag() { return imag; }
	Complex(double r, double imag) :real(r), imag(imag) {};
	Complex operator+(double r);
	friend Complex operator+(double r, const Complex& s);//友元
};
Complex Complex::operator+(double r) {//可以解释a+5
	return Complex(r + real, imag);
}
Complex operator+(double r, const Complex& s) {//普通函数
	return Complex(r + s.real,s.imag);
}
int main() {
	Complex a(1,2);
	a = a + 5;//等价于a.operator+(5);
	a = 5 + a;//ok了
	cout << a.GetReal() << "," << a.Getimag() << endl;
}

运行结果:

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值