任务描述
本关与第一关一模一样,只是运算符重载的返回类型使用了 const
作为修饰。至于为什么要使用 const
修饰,留给大家自行查找原因。
原则上,像算术运算符这样的运算符重载,倾向于使用普通函数进行重载。
相关知识
为什么算术运算符重载的返回类型要使用 const
修饰呢?因为如果不使用 const
修饰,如下代码就有可能通过编译。
-
Int a,b,c; a + b = c;
如上代码通过编译会造成什么后果呢?什么后果也没有。但是再进一步就有可能了。
-
if ( a + b = c ){...}
在表示条件判断的表达式中,把“等于号运算符”误写成“赋值运算符”,应该是每个 C/C++ 程序员犯过的错误。更糟糕的是,编译器不会认为这是错误。这是一个极其危险的错误。
当然,要达成这一“编译器不认为是错误”的错误,还需 2 个条件:第一,加号运算符返回的不是 const
;第二,赋值运算符的返回类型能够经过一次转型转为 bool
类型。
所以,你现在理解为什么最好加上 const
了吗?
编程要求
根据提示,在右侧编辑器的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;} };//记住这里有一个分号 //算术运算符重载 const Int operator + (Int const&lhs,Int const&rhs); const Int operator - (Int const&lhs,Int const&rhs); const Int operator * (Int const&lhs,Int const&rhs); const Int operator / (Int const&lhs,Int const&rhs); const 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;
const Int operator+(Int const&lhs,Int const&rhs)
{
Int m;
m.setValue(lhs.getValue()+rhs.getValue());
return m;
}
const Int operator-(Int const&lhs,Int const&rhs)
{
Int m;
m.setValue(lhs.getValue()-rhs.getValue());
return m;
}
const Int operator*(Int const&lhs,Int const&rhs)
{
Int m;
m.setValue(lhs.getValue()*rhs.getValue());
return m;
}
const Int operator/(Int const&lhs,Int const&rhs)
{
Int m;
m.setValue(lhs.getValue()/rhs.getValue());
return m;
}
const Int operator%(Int const&lhs,Int const&rhs)
{
Int m;
m.setValue(lhs.getValue()%rhs.getValue());
return m;
}
/********* End ************/