头歌程序设计二(面向对象) |
您所在的位置:网站首页 › 算术运算符的功能 › 头歌程序设计二(面向对象) |
第1关:普通函数重载算术运算符
任务描述
Int 类所保存的内容显然是可以进行算术运算的,因此对 Int 类进行算术运算符重载是一件非常自然的事情。 为 Int 类重载算术运算符,以普通函数的形式。 编程要求根据提示,在右侧编辑器的Begin-End区域内补充代码。 测试说明本关共 3 个文件,Int.h、Int.cpp 和 main.cpp。其中 Int.h 和main.cpp 不得改动,用户只能修改 Int.cpp 中的内容。 /********** BEGIN **********/ #include"Int.h" 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 ***********/ 第2关:成员函数重载算术运算符 任务描述Int 类所保存的内容显然是可以进行算术运算的,因此对 Int 类进行算术运算符重载是一件非常自然的事情。 为 Int 类重载算术运算符,以成员函数的形式。 相关知识算术运算符既可以以成员函数形式重载,也可以以普通函数形式重载。出于某种“对称性”的考虑,一般习惯使用普通函数来重载算术运算符。 需要注意的是,二者取其一。即如果以成员函数形式重载了算术运算符,就不要再以普通函数重载(相同参数的)。反之,亦然。 编程要求根据提示,在右侧编辑器的Begin-End区域内补充代码。 测试说明本关共 3 个文件,Int.h、Int.cpp 和 main.cpp。其中 Int.h 和 main.cpp 不得改动,用户只能修改 Int.cpp 中的内容。 /*********** BEGIN **********/ #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 **********/ 第3关:返回const对象的普通函数重载算术运算符 任务描述本关与第一关一模一样,只是运算符重载的返回类型使用了 const 作为修饰。至于为什么要使用 const 修饰,留给大家自行查找原因。 原则上,像算术运算符这样的运算符重载,倾向于使用普通函数进行重载。 编程要求根据提示,在右侧编辑器的Begin-End区域内补充代码。 测试说明本关共3个文件,Int.h、Int.cpp 和 main.cpp。其中 Int.h 和 main.cpp 不得改动,用户只能修改 Int.cpp 中的内容。 /********* Begin **********/ #include"Int.h" 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 ************/ |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |