# 结构体与模板

xiaoxiao2021-02-28  8

## 1、结构体（关键字struct）

#include<iostream> using namespace std; struct Point { int x, y; Point(int x = 0, int y = 0) : x(x), y(y) {} //列表初始化 }; Point operator + (const Point& A, const Point& B) { return Point(A.x + B.x, A.y + B.y); } ostream& operator << (ostream& out, const Point& p) { out << "(" << p.x << "," << p.y << ")"; return out; } int main() { Point a, b(1, 2); a.x = 3; cout << a + b << "\n"; return 0; }

## 2、模板（关键字template）

template<typename T> T sum(T* begin, T* end) { T *p = begin; T ans = 0; for(T *p = begin; p != end; p++) ans = ans + *p; return ans; }

#include<iostream> using namespace std; struct Point { int x, y; Point(int x = 0, int y = 0) : x(x), y(y) {} }; Point operator + (const Point& A, const Point& B) { return Point(A.x + B.x, A.y + B.y); } ostream& operator << (ostream& out, const Point& p) { out << "(" << p.x << "," << p.y << ")"; return out; } template<typename T> T sum(T* begin, T* end) { T *p = begin; T ans = 0; for(T *p = begin; p != end; p++) ans = ans + *p; return ans; } int main() { double a[] = {1.1, 2.2, 3.3, 4.4}; cout << sum(a, a + 4) << "\n"; Point b[] = {Point(1, 2), Point(3, 4), Point(5, 6), Point(7 ,8)}; cout << sum(b, b + 4) << "\n"; return 0; }

#include<iostream> using namespace std; template <typename T> struct Point { T x, y; Point(T x = 0, T y = 0) : x(x),y(y) {} }; template <typename T> Point<T> operator + (const Point<T>& A, const Point<T>& B) { return Point<T>(A.x + B.x, A.y + B.y); } template <typename T> ostream& operator << (ostream& out, const Point<T>& p) { out << "(" << p.x << "," << p.y << ")"; return out; } int main() { Point<int> a(1, 2), b(3, 4); Point<double> c(1.1, 2.2), d(3.3, 4.4); cout<< a + b << " " << c + d << "\n"; return 0; }