任务描述
Int
类所保存的内容显然是可以进行算术运算的,因此对 Int
类进行算术运算符重载是一件非常自然的事情。
为 Int
类重载算术运算符,以普通函数的形式。
相关知识
运算符重载,相当于一个固定了函数名的函数。以重载加号运算符为例,其函数名就是
operator +
运算符重载不能改变运算符的优先级与结合性,本质上也不能改变参数的数量(即双目运算符重载,必须拥有 2 个形参)。但是,如果以成员函数进行重载,则参数数量需要减一。减掉的那个参数,实际上就是调用该运算符时的类对象。
运算符重载的使用有 2 种形式,运算符形式和函数形式。以加号运算符为例,如果是成员函数形式重载,则:
-
Int a,b,c; c = a + b;//运算符形式调用 c = a.operator + (b);//成员函数形式调用
如果是以普通函数形式重载,则:
-
Int a,b,c; c = a + b; c = operator + (a,b);
出于某种“对称性”的考虑,一般习惯使用普通函数来重载算术运算符。
编程要求
根据提示,在右侧编辑器的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&lhs,Int const&rhs); Int operator - (Int const&lhs,Int const&rhs); Int operator * (Int const&lhs,Int const&rhs); Int operator / (Int const&lhs,Int const&rhs); Int operator % (Int const&lhs,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"Int.h"
#include<iostream>
using namespace std;
Int operator+(Int const&lhs,Int const&rhs)
{
Int m;
m.setValue(lhs.getValue()+rhs.getValue());
return m;
}
Int operator-(Int const&lhs,Int const&rhs)
{
Int m;
m.setValue(lhs.getValue()-rhs.getValue());
return m;
}
Int operator*(Int const&lhs,Int const&rhs)
{
Int m;
m.setValue(lhs.getValue()*rhs.getValue());
return m;
}
Int operator/(Int const&lhs,Int const&rhs)
{
Int m;
m.setValue(lhs.getValue()/rhs.getValue());
return m;
}
Int operator%(Int const&lhs,Int const&rhs)
{
Int m;
m.setValue(lhs.getValue()%rhs.getValue());
return m;
}
/********** END ***********/