模板

以point结构体为例

 1 #include<iostream>
 2 using namespace std;
 3 
 4 template <typename T>
 5 struct Point {
 6   T x, y;
 7   Point(T x=0, T y=0):x(x),y(y) {}
 8 };
 9 
10 template <typename T>
11 Point<T> operator + (const Point<T>& A, const Point<T>& B) {
12   return Point<T>(A.x+B.x, A.y+B.y);
13 }
14 
15 template <typename T>
16 ostream& operator << (ostream &out, const Point<T>& p) {
17   out << "(" << p.x << "," << p.y << ")";
18   return out;
19 }
20 
21 int main() {
22   Point<int> a(1,2), b(3,4);
23   Point<double> c(1.1,2.2), d(3.3,4.4);
24   cout << a+b << " " << c+d << "
";
25   return 0;
26 }
原文地址:https://www.cnblogs.com/cyb123456/p/5798439.html