自已拟定一个解决实际问题的题目,用动态联编机制编程实现(程序存为exp_508.cpp)。
时间: 2024-03-03 22:49:47 浏览: 61
题目:计算器程序
实现一个简单的计算器程序,支持基本的数学运算,如加减乘除,并能处理小数和负数。
程序实现:
```c++
#include <iostream>
using namespace std;
class Calculator {
public:
virtual double calculate(double a, double b) = 0;
};
class Add : public Calculator {
public:
double calculate(double a, double b) {
return a + b;
}
};
class Sub : public Calculator {
public:
double calculate(double a, double b) {
return a - b;
}
};
class Mul : public Calculator {
public:
double calculate(double a, double b) {
return a * b;
}
};
class Div : public Calculator {
public:
double calculate(double a, double b) {
if (b == 0) {
cout << "Error: divide by zero" << endl;
return 0;
}
return a / b;
}
};
int main() {
Calculator *c = nullptr;
double a, b;
char op;
cout << "Please input two numbers and an operator (+, -, *, /): ";
cin >> a >> b >> op;
switch (op) {
case '+':
c = new Add();
break;
case '-':
c = new Sub();
break;
case '*':
c = new Mul();
break;
case '/':
c = new Div();
break;
default:
cout << "Error: invalid operator" << endl;
return 0;
}
cout << "Result: " << c->calculate(a, b) << endl;
delete c;
return 0;
}
```
运行程序,输入两个数字和运算符,即可输出计算结果。程序使用了动态联编机制,根据输入的运算符创建相应的计算器对象,并调用其虚函数进行计算。如果输入的运算符不合法,会输出错误信息。
阅读全文