代码
#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;
}
const Fraction& operator*(const Fraction & other)//重载运算符*
//使用Fraction operator*(const Fraction & other)运行结果一致
{
return Fraction(_top*other.getTop(), _bottom*other.getBottom());
}
int getTop() const { return _top; }
int getBottom() const { return _bottom; }
double getValue() const { return _value; }
private:
int _top;
int _bottom;
double _value;
};
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;
system("pause");
return 0;
}
运行结果及分析
说明在重载运算符返回值没有再重新拷贝,编译器优化过。
局限
不能隐式转换运算符前的数字,需要使用非成员函数运算符重载来解决该问题。