非成员函数实现运算符重载可以实现运算符前后都可以隐式转换成所需的类型进行计算,如:
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;
}