c++实现运算符同级的简单计算器
时间: 2024-06-15 18:06:36 浏览: 13
C++可以通过重载运算符来实现运算符同级的简单计算器。重载运算符允许我们自定义运算符的行为,使其适用于自定义的数据类型。
以下是一个简单的C++代码示例,演示了如何实现一个支持加减乘除四则运算的计算器:
```cpp
#include <iostream>
class Calculator {
private:
double result;
public:
Calculator() {
result = 0.0;
}
Calculator operator+(const Calculator& other) {
Calculator temp;
temp.result = this->result + other.result;
return temp;
}
Calculator operator-(const Calculator& other) {
Calculator temp;
temp.result = this->result - other.result;
return temp;
}
Calculator operator*(const Calculator& other) {
Calculator temp;
temp.result = this->result * other.result;
return temp;
}
Calculator operator/(const Calculator& other) {
if (other.result != 0) {
Calculator temp;
temp.result = this->result / other.result;
return temp;
} else {
std::cout << "Error: Division by zero! << std::endl;
return *this;
}
}
void setValue(double value) {
result = value;
}
double getValue() const {
return result;
}
};
int main() {
Calculator calc1, calc2, result;
calc1.setValue(10.0);
calc2.setValue(5.0);
// 加法
result = calc1 + calc2;
std::cout << "Addition: " << result.getValue() << std::endl;
// 减法
result = calc1 - calc2;
std::cout << "Subtraction: " << result.getValue() << std::endl;
// 乘法
result = calc1 * calc2;
std::cout << "Multiplication: " << result.getValue() << std::endl;
// 除法
result = calc1 / calc2;
std::cout << "Division: " << result.getValue() << std::endl;
return 0;
}
```
在上面的代码中,我们定义了一个名为`Calculator`的类,其中重载了加法运算符`+`、减法运算符`-`、乘法运算符`*`和除法运算符`/`。通过重载这些运算符,我们可以直接对`Calculator`对象进行四则运算。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)