当前位置:   article > 正文

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

成员函数重载算术运算符

任务描述

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

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

相关知识

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

编程要求

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

测试说明

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

Int.h 内容如下:

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

main.cpp 内容如下:

    1. #include "Int.h"
    2. #include <iostream>
    3. using namespace std;
    4. int main(){
    5. int x,y;
    6. cin>>x>>y;
    7. Int a(x),b(y);
    8. Int c,d,e,f,g;
    9. c = a + b;
    10. d = a - b;
    11. e = a * b;
    12. f = a / b;
    13. g = a % b;
    14. cout<<c.getValue()<<" "
    15. <<d.getValue()<<" "
    16. <<e.getValue()<<" "
    17. <<f.getValue()<<" "
    18. <<g.getValue()<<endl;
    19. return 0;
    20. }

 

 

  1. /*********** BEGIN **********/
  2. #include<iostream>
  3. using namespace std;
  4. #include"Int.h"
  5. Int Int::operator+(Int const&rhs)
  6. {
  7. Int m;
  8. m.setValue(getValue()+rhs.getValue());
  9. return m;
  10. }
  11. Int Int::operator-(Int const&rhs)
  12. {
  13. Int m;
  14. m.setValue(getValue()-rhs.getValue());
  15. return m;
  16. }
  17. Int Int::operator*(Int const&rhs)
  18. {
  19. Int m;
  20. m.setValue(getValue()*rhs.getValue());
  21. return m;
  22. }
  23. Int Int::operator/(Int const&rhs)
  24. {
  25. Int m;
  26. m.setValue(getValue()/rhs.getValue());
  27. return m;
  28. }
  29. Int Int::operator%(Int const&rhs)
  30. {
  31. Int m;
  32. m.setValue(getValue()%rhs.getValue());
  33. return m;
  34. }
  35. /********** END **********/

 

 

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/正经夜光杯/article/detail/838228
推荐阅读
相关标签
  

闽ICP备14008679号