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

本文详细介绍了C++中运算符重载的实现方法,特别是对于类成员函数重载运算符*的过程,并讨论了其局限性,如无法直接处理数字与自定义类型的运算。通过具体代码示例,展示了如何在Fraction类中实现乘法运算符的重载,以及如何通过非成员函数解决特定的隐式类型转换问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码

#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;
}

运行结果及分析

重载运算符*
说明在重载运算符返回值没有再重新拷贝,编译器优化过。

局限

不能隐式转换运算符前的数字,需要使用非成员函数运算符重载来解决该问题。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值