c++用类模板写一个工具类,可以有小数,整数,向量的加减乘除
时间: 2023-04-10 14:04:46 浏览: 144
好的,以下是一个使用类模板实现的工具类,可以进行小数、整数和向量的加减乘除运算:
```c++
#include <iostream>
#include <vector>
template <typename T>
class Calculator {
public:
T add(T a, T b) {
return a + b;
}
T subtract(T a, T b) {
return a - b;
}
T multiply(T a, T b) {
return a * b;
}
T divide(T a, T b) {
return a / b;
}
std::vector<T> add(std::vector<T> a, std::vector<T> b) {
std::vector<T> result;
for (int i = 0; i < a.size(); i++) {
result.push_back(a[i] + b[i]);
}
return result;
}
std::vector<T> subtract(std::vector<T> a, std::vector<T> b) {
std::vector<T> result;
for (int i = 0; i < a.size(); i++) {
result.push_back(a[i] - b[i]);
}
return result;
}
std::vector<T> multiply(std::vector<T> a, std::vector<T> b) {
std::vector<T> result;
for (int i = 0; i < a.size(); i++) {
result.push_back(a[i] * b[i]);
}
return result;
}
std::vector<T> divide(std::vector<T> a, std::vector<T> b) {
std::vector<T> result;
for (int i = 0; i < a.size(); i++) {
result.push_back(a[i] / b[i]);
}
return result;
}
};
int main() {
Calculator<int> intCalc;
std::cout << intCalc.add(1, 2) << std::endl;
std::cout << intCalc.subtract(3, 2) << std::endl;
std::cout << intCalc.multiply(2, 3) << std::endl;
std::cout << intCalc.divide(6, 3) << std::endl;
Calculator<double> doubleCalc;
std::cout << doubleCalc.add(1.5, 2.5) << std::endl;
std::cout << doubleCalc.subtract(3.5, 2.5) << std::endl;
std::cout << doubleCalc.multiply(2.5, 3.5) << std::endl;
std::cout << doubleCalc.divide(6.5, 3.5) << std::endl;
Calculator<std::vector<int>> intVecCalc;
std::vector<int> a = {1, 2, 3};
std::vector<int> b = {4, 5, 6};
std::vector<int> c = intVecCalc.add(a, b);
for (int i = 0; i < c.size(); i++) {
std::cout << c[i] << " ";
}
std::cout << std::endl;
Calculator<std::vector<double>> doubleVecCalc;
std::vector<double> d = {1.5, 2.5, 3.5};
std::vector<double> e = {4.5, 5.5, 6.5};
std::vector<double> f = doubleVecCalc.subtract(d, e);
for (int i = 0; i < f.size(); i++) {
std::cout << f[i] << " ";
}
std::cout << std::endl;
return 0;
}
```
希望这个工具类能够满足您的需求!
阅读全文