c++(重载双目运算符)

本文介绍了如何在C++中重载加法运算符,通过一个`feetinches`类的例子展示重载过程。重载函数使用临时对象存储运算结果,并简化了feet和inches的值。执行双目运算符时,会自动调用对象的重载函数,等价于对象调用成员函数`operator+`。

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

重载加法运算符,实现对象的直接加法运算。例如,下面这个feetinches类:

class FeetInches
{
private:
    int feet;
    int inches;
    //对feet和inches的值进行调整
    void simplify();

public:
    FeetInches(int f=0, int i=0)
    {
        feet = f;
        inches = i;
        simplify();
    }
    void setData(int f,int i)
    {
        feet = f;
        inches = i;
        simplify();
    }
    int getFeet(){return feet;}
    int getInches(){return inches;}

    //重载加法运算符
    FeetInches operator+(const FeetInches &right)
    {
        FeetInches temp;
        temp.feet = this->feet + right.feet;
        temp.inches = this->inches + right.inches;
        temp.simplify();
        return temp;
    }
};

其中simplify函数实现对feet和inches的调整,具体实现如下:

void FeetInches::simplify()
{
    if(inches >= 12)
    {
        feet+=inches/12;
        inches = inches%12;
    }else if(inches < 0)
    {
        feet-=abs(inches)/12 + 1;
       
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值