算术运算符重载——成员函数重载算术运算符

任务描述

Int 类所保存的内容显然是可以进行算术运算的,因此对 Int 类进行算术运算符重载是一件非常自然的事情。

Int 类重载算术运算符,以成员函数的形式。

相关知识

算术运算符既可以以成员函数形式重载,也可以以普通函数形式重载。出于某种“对称性”的考虑,一般习惯使用普通函数来重载算术运算符。
需要注意的是,二者取其一。即如果以成员函数形式重载了算术运算符,就不要再以普通函数重载(相同参数的)。反之,亦然。

编程要求

根据提示,在右侧编辑器的Begin-End区域内补充代码。

测试说明

本关共 3 个文件,Int.h、Int.cpp 和 main.cpp。其中 Int.h 和 main.cpp 不得改动,用户只能修改 Int.cpp 中的内容。

Int.h 内容如下:

  1. /**
    * 这是一个包装类(wrapper class),包装类在C++中有点小小的用处(基本上没用),在Java中的用处更大一些。
    */
    
    #ifndef _INT_H_ //这是define guard
    #define _INT_H_ //在C和C++中,头文件都应该有这玩意
    
    class Int{
    private://这是访问控制——私有的
    int value; //这是数据成员,我们称Int是基本类型int的包装类,就是因为Int里面只有一个int类型的数据成员
    
    public: //这是公有的
    Int():value(0){}
    Int(Int const&rhs):value(rhs.value){}
    Int(int v):value(v){}
    
    int getValue()const{return value;}
    void setValue(int v){value=v;}
    
    //成员函数算术运算符重载
    Int operator + (Int const&rhs);
    Int operator - (Int const&rhs);
    Int operator * (Int const&rhs);
    Int operator / (Int const&rhs);
    Int operator % (Int const&rhs);
    
    };//记住这里有一个分号
    
    
    #endif

main.cpp 内容如下:

  1. #include "Int.h"
    #include <iostream>
    using namespace std;
    
    int main(){
    int x,y;
    cin>>x>>y;
    Int a(x),b(y);
    Int c,d,e,f,g;
    
    c = a + b;
    d = a - b;
    e = a * b;
    f = a / b;
    g = a % b;
    
    cout<<c.getValue()<<" "
    <<d.getValue()<<" "
    <<e.getValue()<<" "
    <<f.getValue()<<" "
    <<g.getValue()<<endl;
    
    return 0;
    }

 

 

/*********** BEGIN **********/
#include<iostream>
using namespace std;
#include"Int.h"
Int Int::operator+(Int const&rhs)
{
    Int m;
    m.setValue(getValue()+rhs.getValue());
    return m;
}
Int Int::operator-(Int const&rhs)
{
    Int m;
    m.setValue(getValue()-rhs.getValue());
    return m;
}
Int Int::operator*(Int const&rhs)
{
    Int m;
    m.setValue(getValue()*rhs.getValue());
    return m;
}
Int Int::operator/(Int const&rhs)
{
    Int m;
    m.setValue(getValue()/rhs.getValue());
    return m;
}

Int Int::operator%(Int const&rhs)
{
    Int m;
    m.setValue(getValue()%rhs.getValue());
    return m;
}
/********** END **********/

 

 

  • 9
    点赞
  • 49
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值