diff --git a/class_template.cpp b/class_template.cpp new file mode 100644 index 0000000..5a0fd4c --- /dev/null +++ b/class_template.cpp @@ -0,0 +1,41 @@ +#include +#include + +// 用函数模板求解定积分 +class F1 +{ +public: + double fun(double x) { return x * x; } +}; +class F2 +{ +public: + double fun(double x) { return x; } +}; + +template +class Integrate +{ + double a, b; + int n; + T cf; // 传递被积函数 +public: + Integrate(double _a, double _b, int _n = 10000) : a{_a}, b{_b}, n{_n} {} + double integrate() + { + double result{(cf.fun(a) + cf.fun(b)) / 2}; + double h{(b - a) / n}; + for (int i{1}; i < n; i++) + result += cf.fun(a + i * h); + result *= h; + return result; + } +}; + +int main() +{ + Integrate i1{0, 1}; + Integrate i2{0, 1}; + std::cout << i1.integrate() << '\n' + << i2.integrate(); +}