任务描述
Int
类所保存的内容显然是可以进行算术运算的,因此对 Int
类进行算术运算符重载是一件非常自然的事情。
为 Int
类重载算术运算符,以成员函数的形式。
相关知识
算术运算符既可以以成员函数形式重载,也可以以普通函数形式重载。出于某种“对称性”的考虑,一般习惯使用普通函数来重载算术运算符。
需要注意的是,二者取其一。即如果以成员函数形式重载了算术运算符,就不要再以普通函数重载(相同参数的)。反之,亦然。
编程要求
根据提示,在右侧编辑器的Begin-End区域内补充代码。
测试说明
本关共 3 个文件,Int.h、Int.cpp 和 main.cpp。其中 Int.h 和 main.cpp 不得改动,用户只能修改 Int.cpp 中的内容。
Int.h 内容如下:
-
/** * 这是一个包装类(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 内容如下:
-
#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 **********/