定义一个整数计算类Integer,实现短整数+、-、*、/基本算术运算。要求:可以进行数据范围检查(-32 768~32 767,或自行设定),数据溢出时显示错误信息并中断程序运行。 提示:中断程序可以使用abort()函数。 比如: if(a-x.a<-32768||a-x.a>32767) { cout<<"Data overflow!"<<endl; abort(); }
时间: 2024-03-26 09:40:41 浏览: 30
好的,以下是Integer类的实现代码:
```cpp
#include <iostream>
#include <cstdlib>
class Integer {
public:
Integer(int num = 0) : m_num(num) {}
Integer operator+(const Integer& rhs) const {
int res = m_num + rhs.m_num;
checkOverflow(res);
return Integer(res);
}
Integer operator-(const Integer& rhs) const {
int res = m_num - rhs.m_num;
checkOverflow(res);
return Integer(res);
}
Integer operator*(const Integer& rhs) const {
int res = m_num * rhs.m_num;
checkOverflow(res);
return Integer(res);
}
Integer operator/(const Integer& rhs) const {
if (rhs.m_num == 0) {
std::cout << "Divide by zero!" << std::endl;
abort();
}
int res = m_num / rhs.m_num;
return Integer(res);
}
int getValue() const {
return m_num;
}
private:
int m_num;
void checkOverflow(int num) const {
if (num < -32768 || num > 32767) {
std::cout << "Data overflow!" << std::endl;
abort();
}
}
};
int main() {
Integer a(32767), b(1);
Integer c = a + b;
std::cout << c.getValue() << std::endl;
Integer d(-32768), e(-1);
Integer f = d - e;
std::cout << f.getValue() << std::endl;
Integer g(32767), h(2);
Integer i = g * h;
std::cout << i.getValue() << std::endl;
Integer j(32767), k(0);
Integer l = j / k;
return 0;
}
```
在该类中,checkOverflow函数用于检查数据范围,如果越界则输出错误信息并中断程序运行。getValue函数用于获取当前整数的值。在主函数中,我们可以进行加、减、乘、除四种基本算术运算,并且可以进行数据溢出检查。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)