c++定义一个整数计算类Integer,实现短整数+、-、*、/基本算术运算。要求:可以进行数据范围检查(-32 768~32 767,或自行设定),数据溢出时显示错误信息并中断程序运行。 提示:中断程序可以使用abort()函数。 比如: if(a-x.a<-32768||a-x.a>32767) { cout<<"Data overflow!"<<endl; abort(); }
时间: 2024-03-26 10:39:49 浏览: 18
好的,这是一个定义整数计算类Integer的示例代码,它可以实现短整数加、减、乘、除运算,并且对数据范围进行了检查,防止数据溢出导致程序运行错误。
```c++
#include <iostream>
#include <cstdlib>
class Integer {
public:
Integer(int value = 0) : value_(value) {}
Integer operator+(const Integer& rhs) const {
Integer result(this->value_ + rhs.value_);
checkOverflow(result);
return result;
}
Integer operator-(const Integer& rhs) const {
Integer result(this->value_ - rhs.value_);
checkOverflow(result);
return result;
}
Integer operator*(const Integer& rhs) const {
Integer result(this->value_ * rhs.value_);
checkOverflow(result);
return result;
}
Integer operator/(const Integer& rhs) const {
if (rhs.value_ == 0) {
std::cerr << "divide by zero" << std::endl;
abort();
}
Integer result(this->value_ / rhs.value_);
return result;
}
private:
int value_;
void checkOverflow(const Integer& result) const {
if (result.value_ > 32767 || result.value_ < -32768) {
std::cerr << "Data overflow!" << std::endl;
abort();
}
}
};
int main() {
Integer a(32767);
Integer b(1);
Integer c = a + b;
std::cout << c << std::endl;
Integer d(-32768);
Integer e(-1);
Integer f = d - e;
std::cout << f << std::endl;
Integer g(32767);
Integer h(2);
Integer i = g * h;
std::cout << i << std::endl;
Integer j(32767);
Integer k(0);
Integer l = j / k;
std::cout << l << std::endl;
return 0;
}
```
在这个示例代码中,我们定义了一个整数计算类`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)