簡單寫了一個幾何模板當作練習。
1#include <bits/stdc++.h>
2using namespace std;
3
4template<typename T>
5class Point {
6 T x;
7 T y;
8public:
9 Point() {}
10 Point(const T &x, const T &y): x(x), y(y) {}
11 Point operator+(const Point &r) const {
12 return Point(x + r.x, y + r.y);
13 }
14 Point operator-(const Point &r) const {
15 return Point(x - r.x, y - r.y);
16 }
17 bool operator==(const Point &r) const {
18 return x == r.x && y == r.y;
19 }
20 T dot(const Point &r) const {
21 return x * r.x + y * r.y;
22 }
23 T cross(const Point &r) const {
24 return x * r.y - y * r.x;
25 }
26};
27
28template<typename T>
29class Line {
30 Point<T> p;
31 Point<T> q;
32public:
33 Line() {}
34 Line(const Point<T> &p, const Point<T> &q): p(p), q(q) {}
35 T getLen() const {
36 Point<T> tmp = p - q;
37 return sqrt(tmp.dot(tmp));
38 }
39};
40
41int main() {
42 Point<double> a(0, 0), b(3, 4);
43 Line<double> line(a, b);
44 cout << line.getLen() << endl;
45 return 0;
46}