C++ 非成员函数实现运算符*重载

非成员函数实现运算符重载可以实现运算符前后都可以隐式转换成所需的类型进行计算,如:

	Fraction d = a * 2;//根据a的类型,将2隐式转换为Fraction类型
	Fraction e = 2 * a;

1 非友元非成员函数

当类具有获取参与运算符重载运算的必要私有数据接口时,使用非友元非成员函数。

1.1 代码

#include<iostream>
using namespace std;
class Fraction
{
public:
	Fraction(int top = 0, int bottom = 1) :_top(top), _bottom(bottom) 
	{
		_value = static_cast<double>(_top) / _bottom;
		cout << "调用一次构造函数 " << _top << " " << _bottom << endl;
	}
	int getTop() const { return _top; }//获取私有成员变量的接口
	int getBottom() const { return _bottom; }
	double getValue() const { return _value; }

private:
	int _top;
	int _bottom;
	double _value;
};

const Fraction& operator*(const Fraction&a, const Fraction& b)
{
	return Fraction(a.getTop()*b.getTop(), a.getBottom()*b.getBottom());
}

int main()
{
	Fraction a(2, 5);
	Fraction b = Fraction(3, 4);
	Fraction c = a * b;
	Fraction d = a * 2;//将2隐式转换为Fraction类型
	Fraction e = 2 * a;
	cout << c.getTop() << " " << c.getBottom() <<" "<<c.getValue()<< endl;
	cout << d.getTop() << " " << d.getBottom() << " " << d.getValue() << endl;
	cout << e.getTop() << " " << e.getBottom() << " " << e.getValue() << endl;
	system("pause");
	return 0;
}

1.2 运算结果

非友元非成员函数实现运算符重载

2 友元非成员函数

当类不具有获取参与运算符重载运算的全部必要私有数据接口时,使用友元非成员函数,该函数可以访问类的私有成员。

2.1 代码

#include<iostream>
using namespace std;
class Fraction
{
public:
	Fraction(int top = 0, int bottom = 1) :_top(top), _bottom(bottom) 
	{
		_value = static_cast<double>(_top) / _bottom;
		cout << "调用一次构造函数 " << _top << " " << _bottom << endl;
	}
	double getValue() const { return _value; }
	friend const Fraction& operator*(const Fraction&a, const Fraction& b);

private:
	int _top;
	int _bottom;
	double _value;
};

const Fraction& operator*(const Fraction&a, const Fraction& b)
{
	return Fraction(a._top*b._top, a._bottom*b._bottom);
}

int main()
{
	Fraction a(2, 5);
	Fraction b = Fraction(3, 4);
	Fraction c = a * b;
	Fraction d = a * 2;//将2隐式转换为Fraction类型
	Fraction e = 2 * a;
	cout << c.getValue()<< endl;
	cout << d.getValue() << endl;
	cout << e.getValue() << endl;
	system("pause");
	return 0;
}

2.2 运算结果

友元非成员函数实现运算符重载

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值