在前面定义的整数类的基础上,重载+,-,*,/,支持数类型的相关运算(整数相除的结果依然是整数 )
时间: 2024-03-22 20:37:33 浏览: 14
好的,我已经明白您的问题了。下面是重载运算符的实现代码:
```cpp
class Integer {
public:
Integer(int value = 0) : value_(value) {}
Integer operator+(const Integer& another) const {
return Integer(value_ + another.value_);
}
Integer operator-(const Integer& another) const {
return Integer(value_ - another.value_);
}
Integer operator*(const Integer& another) const {
return Integer(value_ * another.value_);
}
Integer operator/(const Integer& another) const {
return Integer(value_ / another.value_);
}
private:
int value_;
};
```
在这个代码中,我们使用了重载运算符来实现整数类的加减乘除运算。在每个运算符的实现中,我们都创建了一个新的整数对象作为返回值,该对象的值是当前对象和另一个对象的运算结果。这些运算符的实现都非常简单,它们只是简单地将两个整数相加、相减、相乘或相除,并将结果存储在新的整数对象中。
需要注意的是,在除法运算中,我们使用的是整数除法,这意味着结果也是整数,不包含任何小数部分。如果您需要支持小数运算,请使用浮点数类型代替整数类型。
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)