C++定义一个整数计算类Integer,实现短整数+、-、*、/基本算术运算。要求:可以进行数据范围检查(-32 768~32 767,或自行设定),数据溢出时显示错误信息并中断程序运行。 提示:中断程序可以使用abort()函数。
时间: 2024-03-27 13:36:44 浏览: 19
好的,以下是一个简单的Integer类的实现,包括加减乘除四个基本算术运算:
```cpp
#include <iostream>
#include <cstdlib>
class Integer {
public:
Integer(int num) : value(num) {}
Integer operator+(const Integer& other) const {
int result = value + other.value;
check(result);
return Integer(result);
}
Integer operator-(const Integer& other) const {
int result = value - other.value;
check(result);
return Integer(result);
}
Integer operator*(const Integer& other) const {
int result = value * other.value;
check(result);
return Integer(result);
}
Integer operator/(const Integer& other) const {
if (other.value == 0) {
std::cerr << "Error: division by zero\n";
std::abort();
}
int result = value / other.value;
check(result);
return Integer(result);
}
private:
int value;
void check(int num) const {
if (num < -32768 || num > 32767) {
std::cerr << "Error: integer overflow\n";
std::abort();
}
}
};
int main() {
Integer a(100);
Integer b(200);
Integer c = a + b;
std::cout << c << '\n';
c = a - b;
std::cout << c << '\n';
c = a * b;
std::cout << c << '\n';
c = a / b;
std::cout << c << '\n';
Integer d(32768);
Integer e(1);
c = d + e; // should cause integer overflow error
return 0;
}
```
在这个实现中,我们定义了一个Integer类来表示整数,它只有一个私有成员变量value,表示整数的值。然后我们分别实现了加减乘除四个基本运算符的重载,每个运算符重载都会先检查计算结果是否超出了整数数据范围,如果是,就输出错误信息并调用`std::abort()`函数中断程序运行。
在main函数中,我们创建了一些Integer对象,并对它们进行了加减乘除的运算,最后测试了一个溢出的情况。
相关推荐
![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)